From 7622eb1548b232a3a82c387863b2473b10acbbc2 Mon Sep 17 00:00:00 2001 From: saiteja Date: Fri, 23 Aug 2024 11:43:16 +0530 Subject: [PATCH 01/58] feat: added transactions --- keeper/keeper.go | 26 + keeper/msg_server.go | 18 + keeper/store.go | 40 + keys.go | 18 + proto/sdk/avail/v1beta1/tx.proto | 52 +- types/tx.pb.go | 1187 ++++++++++++++++++++++++++++-- 6 files changed, 1295 insertions(+), 46 deletions(-) create mode 100644 keeper/store.go diff --git a/keeper/keeper.go b/keeper/keeper.go index dc6281d..39e04d1 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -1,10 +1,13 @@ package keeper import ( + "errors" + "cosmossdk.io/collections" storetypes2 "cosmossdk.io/store/types" upgradekeeper "cosmossdk.io/x/upgrade/keeper" "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" availblob1 "github.com/vitwit/avail-da-module" "github.com/vitwit/avail-da-module/relayer" "github.com/vitwit/avail-da-module/types" @@ -77,3 +80,26 @@ func NewKeeper( func (k *Keeper) SetRelayer(r *relayer.Relayer) { k.relayer = r } + +func (k *Keeper) SubmitBlob(ctx sdk.Context, req *types.MsgSubmitBlobRequest) (*types.MsgSubmitBlobResponse, error) { + store := ctx.KVStore(k.storeKey) + if IsAlreadyExist(ctx, store, *req.BlocksRange) { + return &types.MsgSubmitBlobResponse{}, errors.New("the range is already processed") + } + err := updateBlobStatus(ctx, store, *req.BlocksRange, PENDING) + return &types.MsgSubmitBlobResponse{}, err +} + +func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatusRequest) (*types.MsgUpdateBlobStatusResponse, error) { + store := ctx.KVStore(k.storeKey) + if !IsAlreadyExist(ctx, store, *req.BlocksRange) { + return &types.MsgUpdateBlobStatusResponse{}, errors.New("the range does not exist") + } + + status := FAILURE + if req.IsSuccess { + status = SUCCESS + } + err := updateBlobStatus(ctx, store, *req.BlocksRange, status) + return &types.MsgUpdateBlobStatusResponse{}, err +} diff --git a/keeper/msg_server.go b/keeper/msg_server.go index 384ab3e..3e74e74 100644 --- a/keeper/msg_server.go +++ b/keeper/msg_server.go @@ -3,6 +3,7 @@ package keeper import ( "context" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/vitwit/avail-da-module/types" ) @@ -37,3 +38,20 @@ func (s msgServer) SetAvailAddress(ctx context.Context, msg *types.MsgSetAvailAd return new(types.MsgSetAvailAddressResponse), nil } + +func (s msgServer) SubmitBlob(ctx context.Context, req *types.MsgSubmitBlobRequest) (*types.MsgSubmitBlobResponse, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return s.k.SubmitBlob(sdkCtx, req) +} + +func (s msgServer) UpdateBlobStatus(ctx context.Context, req *types.MsgUpdateBlobStatusRequest) (*types.MsgUpdateBlobStatusResponse, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return s.k.UpdateBlobStatus(sdkCtx, req) +} + +/* +rpc SubmitBlob(MsgSubmitBlobRequest) returns (MsgSubmitBlobResponse); + + // UpdateBlobStatus + rpc UpdateBlobStatus(MsgUpdateBlobStatusRequest) returns (MsgUpdateBlobStatusResponse); +*/ diff --git a/keeper/store.go b/keeper/store.go new file mode 100644 index 0000000..618e167 --- /dev/null +++ b/keeper/store.go @@ -0,0 +1,40 @@ +package keeper + +import ( + "context" + "encoding/binary" + "errors" + + storetypes2 "cosmossdk.io/store/types" + availblob1 "github.com/vitwit/avail-da-module" + "github.com/vitwit/avail-da-module/types" +) + +const ( + PENDING uint32 = 0 + SUCCESS uint32 = 1 + FAILURE uint32 = 2 +) + +func IsAlreadyExist(ctx context.Context, store storetypes2.KVStore, blocksRange types.Range) bool { + pendingBlobStoreKey := availblob1.PendingBlobsStoreKey(blocksRange) + blobStatus := store.Get(pendingBlobStoreKey) + if blobStatus == nil { + return false + } + return true +} + +func updateBlobStatus(ctx context.Context, store storetypes2.KVStore, blocksRange types.Range, status uint32) error { + if status != PENDING || status != SUCCESS || status != FAILURE { + return errors.New("unknown status") + } + pendingBlobStoreKey := availblob1.PendingBlobsStoreKey(blocksRange) + + statusBytes := make([]byte, 4) + + binary.BigEndian.PutUint32(statusBytes, status) + + store.Set(pendingBlobStoreKey, statusBytes) + return nil +} diff --git a/keys.go b/keys.go index a4d4219..641f2bd 100644 --- a/keys.go +++ b/keys.go @@ -1,7 +1,10 @@ package availblob import ( + "encoding/binary" + "cosmossdk.io/collections" + "github.com/vitwit/avail-da-module/types" ) var ( @@ -23,6 +26,8 @@ var ( // light client store key ClientStoreKey = []byte("client_store/") + + PendingBlobsKey = collections.NewPrefix(5) ) const ( @@ -41,3 +46,16 @@ const ( // TransientStoreKey defines the transient store key TransientStoreKey = "transient_" + ModuleName ) + +func PendingBlobsStoreKey(blocksRange types.Range) []byte { + fromBytes := make([]byte, 8) + binary.BigEndian.PutUint64(fromBytes, uint64(blocksRange.From)) + + toBytes := make([]byte, 8) + binary.BigEndian.PutUint64(toBytes, uint64(blocksRange.To)) + + key := PendingBlobsKey + key = append(key, fromBytes...) + key = append(key, toBytes...) + return key +} diff --git a/proto/sdk/avail/v1beta1/tx.proto b/proto/sdk/avail/v1beta1/tx.proto index de7f4a3..5276500 100644 --- a/proto/sdk/avail/v1beta1/tx.proto +++ b/proto/sdk/avail/v1beta1/tx.proto @@ -2,6 +2,7 @@ syntax = "proto3"; package sdk.avail.v1beta1; import "cosmos/msg/v1/msg.proto"; +import "gogoproto/gogo.proto"; option go_package = "github.com/vitwit/avail-da-module/types"; @@ -11,6 +12,12 @@ service Msg { // SetAvailAddress rpc SetAvailAddress(MsgSetAvailAddress) returns (MsgSetAvailAddressResponse); + + // SubmitBlob + rpc SubmitBlob(MsgSubmitBlobRequest) returns (MsgSubmitBlobResponse); + + // UpdateBlobStatus + rpc UpdateBlobStatus(MsgUpdateBlobStatusRequest) returns (MsgUpdateBlobStatusResponse); } // MsgSetAvailAddress defines a SDK message for validators to set their Avail address @@ -23,4 +30,47 @@ message MsgSetAvailAddress { } // MsgSetAvailAddressResponse is the response type for the Msg/SetAvailAddress RPC method. -message MsgSetAvailAddressResponse {} \ No newline at end of file +message MsgSetAvailAddressResponse {} + +// MsgSetAvailAddress defines a SDK message for validators to set their Avail address +message MsgSubmitBlobRequest { + option (cosmos.msg.v1.signer) = "validator_address"; + + string validator_address = 1; + + Range blocks_range = 2; +} + +// blocks range from to to +message Range { + uint64 from = 1; + uint64 to = 2; +} + +// MsgSetAvailAddressResponse is the response type for the Msg/SetAvailAddress RPC method. +message MsgSubmitBlobResponse {} + +// message update blob state response +message MsgUpdateBlobStatusRequest { + option (cosmos.msg.v1.signer) = "validator_address"; + + string validator_address = 1; + Range blocks_range = 2; + uint64 avail_height = 3; + bool is_success = 4; + +} + +// status of submitblob +enum BlobStatus { + option (gogoproto.goproto_enum_prefix) = false; + BLOB_STATUS_UNSPECIFIED = 0; + BLOB_STATUS_FAILURE = 1; + BLOB_STATUS_SUCCESS = 2; + BLOB_STATUS_PENDING = 3; + +} + +// message update blob state response +message MsgUpdateBlobStatusResponse { +} \ No newline at end of file diff --git a/types/tx.pb.go b/types/tx.pb.go index 6224a55..d7d81f4 100644 --- a/types/tx.pb.go +++ b/types/tx.pb.go @@ -7,6 +7,7 @@ import ( context "context" fmt "fmt" _ "github.com/cosmos/cosmos-sdk/types/msgservice" + _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" proto "github.com/cosmos/gogoproto/proto" grpc "google.golang.org/grpc" @@ -28,6 +29,38 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +// status of submitblob +type BlobStatus int32 + +const ( + BLOB_STATUS_UNSPECIFIED BlobStatus = 0 + BLOB_STATUS_FAILURE BlobStatus = 1 + BLOB_STATUS_SUCCESS BlobStatus = 2 + BLOB_STATUS_PENDING BlobStatus = 3 +) + +var BlobStatus_name = map[int32]string{ + 0: "BLOB_STATUS_UNSPECIFIED", + 1: "BLOB_STATUS_FAILURE", + 2: "BLOB_STATUS_SUCCESS", + 3: "BLOB_STATUS_PENDING", +} + +var BlobStatus_value = map[string]int32{ + "BLOB_STATUS_UNSPECIFIED": 0, + "BLOB_STATUS_FAILURE": 1, + "BLOB_STATUS_SUCCESS": 2, + "BLOB_STATUS_PENDING": 3, +} + +func (x BlobStatus) String() string { + return proto.EnumName(BlobStatus_name, int32(x)) +} + +func (BlobStatus) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_7f88203cb33986bc, []int{0} +} + // MsgSetAvailAddress defines a SDK message for validators to set their Avail address type MsgSetAvailAddress struct { ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` @@ -118,32 +151,306 @@ func (m *MsgSetAvailAddressResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgSetAvailAddressResponse proto.InternalMessageInfo +// MsgSetAvailAddress defines a SDK message for validators to set their Avail address +type MsgSubmitBlobRequest struct { + ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` + BlocksRange *Range `protobuf:"bytes,2,opt,name=blocks_range,json=blocksRange,proto3" json:"blocks_range,omitempty"` +} + +func (m *MsgSubmitBlobRequest) Reset() { *m = MsgSubmitBlobRequest{} } +func (m *MsgSubmitBlobRequest) String() string { return proto.CompactTextString(m) } +func (*MsgSubmitBlobRequest) ProtoMessage() {} +func (*MsgSubmitBlobRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_7f88203cb33986bc, []int{2} +} +func (m *MsgSubmitBlobRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSubmitBlobRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSubmitBlobRequest.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 *MsgSubmitBlobRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSubmitBlobRequest.Merge(m, src) +} +func (m *MsgSubmitBlobRequest) XXX_Size() int { + return m.Size() +} +func (m *MsgSubmitBlobRequest) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSubmitBlobRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSubmitBlobRequest proto.InternalMessageInfo + +func (m *MsgSubmitBlobRequest) GetValidatorAddress() string { + if m != nil { + return m.ValidatorAddress + } + return "" +} + +func (m *MsgSubmitBlobRequest) GetBlocksRange() *Range { + if m != nil { + return m.BlocksRange + } + return nil +} + +// blocks range from to to +type Range struct { + From uint64 `protobuf:"varint,1,opt,name=from,proto3" json:"from,omitempty"` + To uint64 `protobuf:"varint,2,opt,name=to,proto3" json:"to,omitempty"` +} + +func (m *Range) Reset() { *m = Range{} } +func (m *Range) String() string { return proto.CompactTextString(m) } +func (*Range) ProtoMessage() {} +func (*Range) Descriptor() ([]byte, []int) { + return fileDescriptor_7f88203cb33986bc, []int{3} +} +func (m *Range) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Range) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Range.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 *Range) XXX_Merge(src proto.Message) { + xxx_messageInfo_Range.Merge(m, src) +} +func (m *Range) XXX_Size() int { + return m.Size() +} +func (m *Range) XXX_DiscardUnknown() { + xxx_messageInfo_Range.DiscardUnknown(m) +} + +var xxx_messageInfo_Range proto.InternalMessageInfo + +func (m *Range) GetFrom() uint64 { + if m != nil { + return m.From + } + return 0 +} + +func (m *Range) GetTo() uint64 { + if m != nil { + return m.To + } + return 0 +} + +// MsgSetAvailAddressResponse is the response type for the Msg/SetAvailAddress RPC method. +type MsgSubmitBlobResponse struct { +} + +func (m *MsgSubmitBlobResponse) Reset() { *m = MsgSubmitBlobResponse{} } +func (m *MsgSubmitBlobResponse) String() string { return proto.CompactTextString(m) } +func (*MsgSubmitBlobResponse) ProtoMessage() {} +func (*MsgSubmitBlobResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_7f88203cb33986bc, []int{4} +} +func (m *MsgSubmitBlobResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSubmitBlobResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSubmitBlobResponse.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 *MsgSubmitBlobResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSubmitBlobResponse.Merge(m, src) +} +func (m *MsgSubmitBlobResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgSubmitBlobResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSubmitBlobResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSubmitBlobResponse proto.InternalMessageInfo + +// message update blob state response +type MsgUpdateBlobStatusRequest struct { + ValidatorAddress string `protobuf:"bytes,1,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` + BlocksRange *Range `protobuf:"bytes,2,opt,name=blocks_range,json=blocksRange,proto3" json:"blocks_range,omitempty"` + AvailHeight uint64 `protobuf:"varint,3,opt,name=avail_height,json=availHeight,proto3" json:"avail_height,omitempty"` + IsSuccess bool `protobuf:"varint,4,opt,name=is_success,json=isSuccess,proto3" json:"is_success,omitempty"` +} + +func (m *MsgUpdateBlobStatusRequest) Reset() { *m = MsgUpdateBlobStatusRequest{} } +func (m *MsgUpdateBlobStatusRequest) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateBlobStatusRequest) ProtoMessage() {} +func (*MsgUpdateBlobStatusRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_7f88203cb33986bc, []int{5} +} +func (m *MsgUpdateBlobStatusRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateBlobStatusRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateBlobStatusRequest.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 *MsgUpdateBlobStatusRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateBlobStatusRequest.Merge(m, src) +} +func (m *MsgUpdateBlobStatusRequest) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateBlobStatusRequest) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateBlobStatusRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateBlobStatusRequest proto.InternalMessageInfo + +func (m *MsgUpdateBlobStatusRequest) GetValidatorAddress() string { + if m != nil { + return m.ValidatorAddress + } + return "" +} + +func (m *MsgUpdateBlobStatusRequest) GetBlocksRange() *Range { + if m != nil { + return m.BlocksRange + } + return nil +} + +func (m *MsgUpdateBlobStatusRequest) GetAvailHeight() uint64 { + if m != nil { + return m.AvailHeight + } + return 0 +} + +func (m *MsgUpdateBlobStatusRequest) GetIsSuccess() bool { + if m != nil { + return m.IsSuccess + } + return false +} + +// message update blob state response +type MsgUpdateBlobStatusResponse struct { +} + +func (m *MsgUpdateBlobStatusResponse) Reset() { *m = MsgUpdateBlobStatusResponse{} } +func (m *MsgUpdateBlobStatusResponse) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateBlobStatusResponse) ProtoMessage() {} +func (*MsgUpdateBlobStatusResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_7f88203cb33986bc, []int{6} +} +func (m *MsgUpdateBlobStatusResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateBlobStatusResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateBlobStatusResponse.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 *MsgUpdateBlobStatusResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateBlobStatusResponse.Merge(m, src) +} +func (m *MsgUpdateBlobStatusResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateBlobStatusResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateBlobStatusResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateBlobStatusResponse proto.InternalMessageInfo + func init() { + proto.RegisterEnum("sdk.avail.v1beta1.BlobStatus", BlobStatus_name, BlobStatus_value) proto.RegisterType((*MsgSetAvailAddress)(nil), "sdk.avail.v1beta1.MsgSetAvailAddress") proto.RegisterType((*MsgSetAvailAddressResponse)(nil), "sdk.avail.v1beta1.MsgSetAvailAddressResponse") + proto.RegisterType((*MsgSubmitBlobRequest)(nil), "sdk.avail.v1beta1.MsgSubmitBlobRequest") + proto.RegisterType((*Range)(nil), "sdk.avail.v1beta1.Range") + proto.RegisterType((*MsgSubmitBlobResponse)(nil), "sdk.avail.v1beta1.MsgSubmitBlobResponse") + proto.RegisterType((*MsgUpdateBlobStatusRequest)(nil), "sdk.avail.v1beta1.MsgUpdateBlobStatusRequest") + proto.RegisterType((*MsgUpdateBlobStatusResponse)(nil), "sdk.avail.v1beta1.MsgUpdateBlobStatusResponse") } func init() { proto.RegisterFile("sdk/avail/v1beta1/tx.proto", fileDescriptor_7f88203cb33986bc) } var fileDescriptor_7f88203cb33986bc = []byte{ - // 272 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2a, 0x4e, 0xc9, 0xd6, - 0x4f, 0x2c, 0x4b, 0xcc, 0xcc, 0xd1, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x2f, 0xa9, - 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x2c, 0x4e, 0xc9, 0xd6, 0x03, 0xcb, 0xe9, 0x41, - 0xe5, 0xa4, 0xc4, 0x93, 0xf3, 0x8b, 0x73, 0xf3, 0x8b, 0xf5, 0x73, 0x8b, 0xd3, 0xf5, 0xcb, 0x0c, - 0x41, 0x14, 0x44, 0xad, 0x52, 0x1d, 0x97, 0x90, 0x6f, 0x71, 0x7a, 0x70, 0x6a, 0x89, 0x23, 0x48, - 0xbd, 0x63, 0x4a, 0x4a, 0x51, 0x6a, 0x71, 0xb1, 0x90, 0x36, 0x97, 0x60, 0x59, 0x62, 0x4e, 0x66, - 0x4a, 0x62, 0x49, 0x7e, 0x51, 0x7c, 0x22, 0x44, 0x50, 0x82, 0x51, 0x81, 0x51, 0x83, 0x33, 0x48, - 0x00, 0x2e, 0x01, 0x53, 0xac, 0xcc, 0xc5, 0x0b, 0xb6, 0x0c, 0xae, 0x90, 0x09, 0xac, 0x90, 0x27, - 0x11, 0xc9, 0x44, 0x2b, 0xb1, 0xa6, 0xe7, 0x1b, 0xb4, 0x30, 0x0d, 0x55, 0x92, 0xe1, 0x92, 0xc2, - 0xb4, 0x3f, 0x28, 0xb5, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0xd5, 0xa8, 0x94, 0x8b, 0xd9, 0xb7, 0x38, - 0x5d, 0x28, 0x9d, 0x8b, 0x1f, 0xdd, 0x85, 0xaa, 0x7a, 0x18, 0x9e, 0xd4, 0xc3, 0x34, 0x48, 0x4a, - 0x97, 0x28, 0x65, 0x30, 0xfb, 0xa4, 0x58, 0x1b, 0x9e, 0x6f, 0xd0, 0x62, 0x74, 0x72, 0x3c, 0xf1, - 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, - 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xf5, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, - 0xbd, 0xe4, 0xfc, 0x5c, 0xfd, 0xb2, 0xcc, 0x92, 0xf2, 0xcc, 0x12, 0x48, 0x24, 0xe8, 0xa6, 0x24, - 0xea, 0xe6, 0xe6, 0xa7, 0x94, 0xe6, 0xa4, 0xea, 0x97, 0x54, 0x16, 0xa4, 0x16, 0x27, 0xb1, 0x81, - 0x83, 0xd7, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x90, 0xc2, 0xec, 0xc5, 0xa8, 0x01, 0x00, 0x00, + // 565 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x54, 0x3d, 0x6f, 0xd3, 0x50, + 0x14, 0x8d, 0x93, 0x14, 0xd1, 0x9b, 0x02, 0xee, 0xa3, 0x90, 0xc8, 0xa5, 0x56, 0x09, 0x42, 0x8d, + 0x52, 0xc5, 0x56, 0xca, 0x06, 0x53, 0x92, 0xa6, 0x10, 0xa9, 0x0d, 0x95, 0xdd, 0x2c, 0x2c, 0xd6, + 0x73, 0xfc, 0x70, 0xac, 0xc4, 0x7d, 0x69, 0xde, 0x73, 0xf8, 0x18, 0x10, 0x62, 0x62, 0x64, 0x64, + 0xe7, 0x0f, 0xf4, 0x67, 0xc0, 0xd6, 0x91, 0xb1, 0x4a, 0x86, 0xfe, 0x0d, 0xe4, 0xe7, 0xf4, 0x43, + 0x4e, 0x2d, 0xca, 0xc2, 0x94, 0x97, 0x73, 0x8e, 0xef, 0x3d, 0xe7, 0xfa, 0xfa, 0x81, 0xc2, 0x9c, + 0xbe, 0x8e, 0xc7, 0xd8, 0x1b, 0xe8, 0xe3, 0xaa, 0x4d, 0x38, 0xae, 0xea, 0xfc, 0xbd, 0x36, 0x1c, + 0x51, 0x4e, 0xd1, 0x32, 0x73, 0xfa, 0x9a, 0xe0, 0xb4, 0x19, 0xa7, 0xe4, 0xbb, 0x94, 0xf9, 0x94, + 0xe9, 0x3e, 0x73, 0xf5, 0x71, 0x35, 0xfc, 0x89, 0xb4, 0xca, 0x8a, 0x4b, 0x5d, 0x2a, 0x8e, 0x7a, + 0x78, 0x8a, 0xd0, 0xe2, 0x27, 0x40, 0x7b, 0xcc, 0x35, 0x09, 0xaf, 0x85, 0x55, 0x6a, 0x8e, 0x33, + 0x22, 0x8c, 0xa1, 0x4d, 0x58, 0x1e, 0xe3, 0x81, 0xe7, 0x60, 0x4e, 0x47, 0x16, 0x8e, 0xc0, 0x82, + 0xb4, 0x2e, 0x95, 0x16, 0x0d, 0xf9, 0x82, 0x38, 0x17, 0x3f, 0x81, 0x3b, 0xc2, 0xc2, 0x85, 0x30, + 0x2d, 0x84, 0x4b, 0xf8, 0x4a, 0xc5, 0xe7, 0x0f, 0xbf, 0x9c, 0x1d, 0x97, 0xe7, 0x8b, 0x16, 0x1f, + 0x81, 0x32, 0xdf, 0xdf, 0x20, 0x6c, 0x48, 0x0f, 0x19, 0x29, 0x7e, 0x97, 0x60, 0x25, 0xa4, 0x03, + 0xdb, 0xf7, 0x78, 0x7d, 0x40, 0x6d, 0x83, 0x1c, 0x05, 0x84, 0xf1, 0x7f, 0x33, 0xf8, 0x02, 0x96, + 0xec, 0x01, 0xed, 0xf6, 0x99, 0x35, 0xc2, 0x87, 0x2e, 0x11, 0xfe, 0x72, 0x5b, 0x05, 0x6d, 0x6e, + 0x78, 0x9a, 0x11, 0xf2, 0x46, 0x2e, 0x52, 0x8b, 0x3f, 0x89, 0xc6, 0x37, 0x61, 0x41, 0x08, 0x10, + 0x82, 0xec, 0xdb, 0x11, 0xf5, 0x45, 0xf7, 0xac, 0x21, 0xce, 0xe8, 0x2e, 0xa4, 0x39, 0x15, 0x7d, + 0xb2, 0x46, 0x9a, 0xd3, 0x62, 0x1e, 0x1e, 0xc4, 0x62, 0xcc, 0x02, 0x9e, 0x4a, 0x22, 0x7f, 0x67, + 0xe8, 0x60, 0x4e, 0x42, 0xc6, 0xe4, 0x98, 0x07, 0xec, 0xbf, 0xc7, 0x44, 0x8f, 0x21, 0x7a, 0x5f, + 0x56, 0x8f, 0x78, 0x6e, 0x8f, 0x17, 0x32, 0xc2, 0x7b, 0x4e, 0x60, 0xaf, 0x04, 0x84, 0xd6, 0x00, + 0x3c, 0x66, 0xb1, 0xa0, 0xdb, 0x0d, 0x5d, 0x64, 0xd7, 0xa5, 0xd2, 0x6d, 0x63, 0xd1, 0x63, 0x66, + 0x04, 0x24, 0x0e, 0x6a, 0x0d, 0x56, 0xaf, 0x4d, 0x18, 0x4d, 0xa0, 0xfc, 0x11, 0xe0, 0x12, 0x45, + 0xab, 0x90, 0xaf, 0xef, 0xbe, 0xae, 0x5b, 0xe6, 0x41, 0xed, 0xa0, 0x63, 0x5a, 0x9d, 0xb6, 0xb9, + 0xdf, 0x6c, 0xb4, 0x76, 0x5a, 0xcd, 0x6d, 0x39, 0x85, 0xf2, 0x70, 0xff, 0x2a, 0xb9, 0x53, 0x6b, + 0xed, 0x76, 0x8c, 0xa6, 0x2c, 0xc5, 0x09, 0xb3, 0xd3, 0x68, 0x34, 0x4d, 0x53, 0x4e, 0xc7, 0x89, + 0xfd, 0x66, 0x7b, 0xbb, 0xd5, 0x7e, 0x29, 0x67, 0x94, 0xec, 0xd7, 0x1f, 0x6a, 0x6a, 0xeb, 0x57, + 0x1a, 0x32, 0x7b, 0xcc, 0x45, 0x2e, 0xdc, 0x8b, 0x7f, 0x01, 0x4f, 0xaf, 0x19, 0xdb, 0xfc, 0xa2, + 0x2a, 0x95, 0x1b, 0xc9, 0xce, 0xc3, 0x22, 0x0b, 0xe0, 0x72, 0x09, 0xd0, 0x46, 0xc2, 0xc3, 0xf1, + 0x6d, 0x57, 0x4a, 0x7f, 0x17, 0xce, 0x1a, 0x1c, 0x81, 0x1c, 0x9f, 0x34, 0x4a, 0xf0, 0x98, 0xb0, + 0x73, 0x8a, 0x76, 0x53, 0x79, 0xd4, 0x52, 0x59, 0xf8, 0x7c, 0x76, 0x5c, 0x96, 0xea, 0xb5, 0x9f, + 0x13, 0x55, 0x3a, 0x99, 0xa8, 0xd2, 0xe9, 0x44, 0x95, 0xbe, 0x4d, 0xd5, 0xd4, 0xc9, 0x54, 0x4d, + 0xfd, 0x9e, 0xaa, 0xa9, 0x37, 0x1b, 0xae, 0xc7, 0x7b, 0x81, 0xad, 0x75, 0xa9, 0xaf, 0x8f, 0x3d, + 0xfe, 0xce, 0xe3, 0xd1, 0x75, 0x56, 0x71, 0x70, 0xc5, 0xa7, 0x4e, 0x30, 0x20, 0x3a, 0xff, 0x30, + 0x24, 0xcc, 0xbe, 0x25, 0xae, 0xa4, 0x67, 0x7f, 0x02, 0x00, 0x00, 0xff, 0xff, 0x86, 0x7e, 0xfe, + 0xc2, 0xf2, 0x04, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -160,6 +467,10 @@ const _ = grpc.SupportPackageIsVersion4 type MsgClient interface { // SetAvailAddress SetAvailAddress(ctx context.Context, in *MsgSetAvailAddress, opts ...grpc.CallOption) (*MsgSetAvailAddressResponse, error) + // SubmitBlob + SubmitBlob(ctx context.Context, in *MsgSubmitBlobRequest, opts ...grpc.CallOption) (*MsgSubmitBlobResponse, error) + // UpdateBlobStatus + UpdateBlobStatus(ctx context.Context, in *MsgUpdateBlobStatusRequest, opts ...grpc.CallOption) (*MsgUpdateBlobStatusResponse, error) } type msgClient struct { @@ -179,10 +490,32 @@ func (c *msgClient) SetAvailAddress(ctx context.Context, in *MsgSetAvailAddress, return out, nil } +func (c *msgClient) SubmitBlob(ctx context.Context, in *MsgSubmitBlobRequest, opts ...grpc.CallOption) (*MsgSubmitBlobResponse, error) { + out := new(MsgSubmitBlobResponse) + err := c.cc.Invoke(ctx, "/sdk.avail.v1beta1.Msg/SubmitBlob", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) UpdateBlobStatus(ctx context.Context, in *MsgUpdateBlobStatusRequest, opts ...grpc.CallOption) (*MsgUpdateBlobStatusResponse, error) { + out := new(MsgUpdateBlobStatusResponse) + err := c.cc.Invoke(ctx, "/sdk.avail.v1beta1.Msg/UpdateBlobStatus", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // MsgServer is the server API for Msg service. type MsgServer interface { // SetAvailAddress SetAvailAddress(context.Context, *MsgSetAvailAddress) (*MsgSetAvailAddressResponse, error) + // SubmitBlob + SubmitBlob(context.Context, *MsgSubmitBlobRequest) (*MsgSubmitBlobResponse, error) + // UpdateBlobStatus + UpdateBlobStatus(context.Context, *MsgUpdateBlobStatusRequest) (*MsgUpdateBlobStatusResponse, error) } // UnimplementedMsgServer can be embedded to have forward compatible implementations. @@ -192,6 +525,12 @@ type UnimplementedMsgServer struct { func (*UnimplementedMsgServer) SetAvailAddress(ctx context.Context, req *MsgSetAvailAddress) (*MsgSetAvailAddressResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method SetAvailAddress not implemented") } +func (*UnimplementedMsgServer) SubmitBlob(ctx context.Context, req *MsgSubmitBlobRequest) (*MsgSubmitBlobResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SubmitBlob not implemented") +} +func (*UnimplementedMsgServer) UpdateBlobStatus(ctx context.Context, req *MsgUpdateBlobStatusRequest) (*MsgUpdateBlobStatusResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateBlobStatus not implemented") +} func RegisterMsgServer(s grpc1.Server, srv MsgServer) { s.RegisterService(&_Msg_serviceDesc, srv) @@ -215,6 +554,42 @@ func _Msg_SetAvailAddress_Handler(srv interface{}, ctx context.Context, dec func return interceptor(ctx, in, info, handler) } +func _Msg_SubmitBlob_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgSubmitBlobRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).SubmitBlob(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/sdk.avail.v1beta1.Msg/SubmitBlob", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).SubmitBlob(ctx, req.(*MsgSubmitBlobRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_UpdateBlobStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUpdateBlobStatusRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).UpdateBlobStatus(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/sdk.avail.v1beta1.Msg/UpdateBlobStatus", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateBlobStatus(ctx, req.(*MsgUpdateBlobStatusRequest)) + } + return interceptor(ctx, in, info, handler) +} + var _Msg_serviceDesc = grpc.ServiceDesc{ ServiceName: "sdk.avail.v1beta1.Msg", HandlerType: (*MsgServer)(nil), @@ -223,6 +598,14 @@ var _Msg_serviceDesc = grpc.ServiceDesc{ MethodName: "SetAvailAddress", Handler: _Msg_SetAvailAddress_Handler, }, + { + MethodName: "SubmitBlob", + Handler: _Msg_SubmitBlob_Handler, + }, + { + MethodName: "UpdateBlobStatus", + Handler: _Msg_UpdateBlobStatus_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "sdk/avail/v1beta1/tx.proto", @@ -288,41 +671,292 @@ func (m *MsgSetAvailAddressResponse) MarshalToSizedBuffer(dAtA []byte) (int, err 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++ +func (m *MsgSubmitBlobRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - dAtA[offset] = uint8(v) - return base + return dAtA[:n], nil } -func (m *MsgSetAvailAddress) Size() (n int) { - if m == nil { - return 0 - } + +func (m *MsgSubmitBlobRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSubmitBlobRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = len(m.ValidatorAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if m.BlocksRange != nil { + { + size, err := m.BlocksRange.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 } - l = len(m.AvailAddress) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if len(m.ValidatorAddress) > 0 { + i -= len(m.ValidatorAddress) + copy(dAtA[i:], m.ValidatorAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.ValidatorAddress))) + i-- + dAtA[i] = 0xa } - return n + return len(dAtA) - i, nil } -func (m *MsgSetAvailAddressResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n +func (m *Range) 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 *Range) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Range) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.To != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.To)) + i-- + dAtA[i] = 0x10 + } + if m.From != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.From)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *MsgSubmitBlobResponse) 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 *MsgSubmitBlobResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSubmitBlobResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgUpdateBlobStatusRequest) 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 *MsgUpdateBlobStatusRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateBlobStatusRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.IsSuccess { + i-- + if m.IsSuccess { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x20 + } + if m.AvailHeight != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.AvailHeight)) + i-- + dAtA[i] = 0x18 + } + if m.BlocksRange != nil { + { + size, err := m.BlocksRange.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.ValidatorAddress) > 0 { + i -= len(m.ValidatorAddress) + copy(dAtA[i:], m.ValidatorAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.ValidatorAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUpdateBlobStatusResponse) 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 *MsgUpdateBlobStatusResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateBlobStatusResponse) 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 *MsgSetAvailAddress) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ValidatorAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.AvailAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgSetAvailAddressResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgSubmitBlobRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ValidatorAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.BlocksRange != nil { + l = m.BlocksRange.Size() + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *Range) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.From != 0 { + n += 1 + sovTx(uint64(m.From)) + } + if m.To != 0 { + n += 1 + sovTx(uint64(m.To)) + } + return n +} + +func (m *MsgSubmitBlobResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgUpdateBlobStatusRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ValidatorAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.BlocksRange != nil { + l = m.BlocksRange.Size() + n += 1 + l + sovTx(uint64(l)) + } + if m.AvailHeight != 0 { + n += 1 + sovTx(uint64(m.AvailHeight)) + } + if m.IsSuccess { + n += 2 + } + return n +} + +func (m *MsgUpdateBlobStatusResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n } func sovTx(x uint64) (n int) { @@ -495,6 +1129,469 @@ func (m *MsgSetAvailAddressResponse) Unmarshal(dAtA []byte) error { } return nil } +func (m *MsgSubmitBlobRequest) 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: MsgSubmitBlobRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSubmitBlobRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", 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.ValidatorAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlocksRange", 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 + } + if m.BlocksRange == nil { + m.BlocksRange = &Range{} + } + if err := m.BlocksRange.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 *Range) 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: Range: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Range: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) + } + m.From = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.From |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field To", wireType) + } + m.To = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.To |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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 *MsgSubmitBlobResponse) 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: MsgSubmitBlobResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSubmitBlobResponse: 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 *MsgUpdateBlobStatusRequest) 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: MsgUpdateBlobStatusRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateBlobStatusRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", 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.ValidatorAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BlocksRange", 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 + } + if m.BlocksRange == nil { + m.BlocksRange = &Range{} + } + if err := m.BlocksRange.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AvailHeight", wireType) + } + m.AvailHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.AvailHeight |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field IsSuccess", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.IsSuccess = bool(v != 0) + 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 *MsgUpdateBlobStatusResponse) 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: MsgUpdateBlobStatusResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateBlobStatusResponse: 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 From 22ed2eb64d70735c3c057432906fb3e535743db4 Mon Sep 17 00:00:00 2001 From: saiteja Date: Fri, 23 Aug 2024 12:21:23 +0530 Subject: [PATCH 02/58] feat: implement client --- client/cli/tx.go | 111 +++++++++++++++++++++++++++++++++++++++++++ keeper/keeper.go | 3 ++ keeper/msg_server.go | 5 ++ keeper/store.go | 2 + types/codec.go | 4 ++ 5 files changed, 125 insertions(+) diff --git a/client/cli/tx.go b/client/cli/tx.go index e2d66ef..731bc90 100644 --- a/client/cli/tx.go +++ b/client/cli/tx.go @@ -1,11 +1,18 @@ package cli import ( + "errors" + "strconv" + "strings" + "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" availblob "github.com/vitwit/avail-da-module" + "github.com/vitwit/avail-da-module/types" ) // NewTxCmd @@ -18,5 +25,109 @@ func NewTxCmd() *cobra.Command { RunE: client.ValidateCmd, } + txCmd.AddCommand(NewSubmitBlobCmd()) + txCmd.AddCommand(NewUpdateBlobStatusCmd()) return txCmd } + +// submit blob +func NewSubmitBlobCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "submit-blob [from_block] [to_block]", + Short: "request to submit blob with blocks from [from] to [to]", + Example: "submit-blob 11 15", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + fromBlock, err := strconv.Atoi(args[0]) + if err != nil { + return err + } + toBlock, err := strconv.Atoi(args[1]) + if err != nil { + return err + } + + msg := types.MsgSubmitBlobRequest{ + BlocksRange: &types.Range{ + From: uint64(fromBlock), + To: uint64(toBlock), + }, + ValidatorAddress: clientCtx.GetFromAddress().String(), + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} + +// update status +func NewUpdateBlobStatusCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "update-blob [from_block] [to_block] [status] [avail_height]", + Short: `update blob status by giving blocks range and status(success|failure) + and the avail height at which the blob is stored`, + Example: "update-blob 11 15 success 120", + Args: cobra.ExactArgs(4), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + fromBlock, err := strconv.Atoi(args[0]) + if err != nil { + return err + } + toBlock, err := strconv.Atoi(args[1]) + if err != nil { + return err + } + + isSuccess, err := ParseStatus(args[2]) + if err != nil { + return err + } + + availHeight, err := strconv.Atoi(args[3]) + if err != nil { + return err + } + + msg := types.MsgUpdateBlobStatusRequest{ + BlocksRange: &types.Range{ + From: uint64(fromBlock), + To: uint64(toBlock), + }, + ValidatorAddress: clientCtx.GetFromAddress().String(), + AvailHeight: uint64(availHeight), + IsSuccess: isSuccess, + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} + +func ParseStatus(status string) (bool, error) { + status = strings.ToUpper(status) + if status == "SUCCESS" { + return true, nil + } + + if status == "FAILURE" { + return false, nil + } + + return false, errors.New("invalid status") +} diff --git a/keeper/keeper.go b/keeper/keeper.go index 39e04d1..2f6c161 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -2,6 +2,7 @@ package keeper import ( "errors" + "fmt" "cosmossdk.io/collections" storetypes2 "cosmossdk.io/store/types" @@ -86,6 +87,8 @@ func (k *Keeper) SubmitBlob(ctx sdk.Context, req *types.MsgSubmitBlobRequest) (* if IsAlreadyExist(ctx, store, *req.BlocksRange) { return &types.MsgSubmitBlobResponse{}, errors.New("the range is already processed") } + + fmt.Println("passed already exist..............") err := updateBlobStatus(ctx, store, *req.BlocksRange, PENDING) return &types.MsgSubmitBlobResponse{}, err } diff --git a/keeper/msg_server.go b/keeper/msg_server.go index 3e74e74..abc5266 100644 --- a/keeper/msg_server.go +++ b/keeper/msg_server.go @@ -2,6 +2,7 @@ package keeper import ( "context" + "fmt" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/vitwit/avail-da-module/types" @@ -40,12 +41,16 @@ func (s msgServer) SetAvailAddress(ctx context.Context, msg *types.MsgSetAvailAd } func (s msgServer) SubmitBlob(ctx context.Context, req *types.MsgSubmitBlobRequest) (*types.MsgSubmitBlobResponse, error) { + + fmt.Println("msgServer sub,itblob.............", req) sdkCtx := sdk.UnwrapSDKContext(ctx) return s.k.SubmitBlob(sdkCtx, req) } func (s msgServer) UpdateBlobStatus(ctx context.Context, req *types.MsgUpdateBlobStatusRequest) (*types.MsgUpdateBlobStatusResponse, error) { sdkCtx := sdk.UnwrapSDKContext(ctx) + + //TODO: query the light client return s.k.UpdateBlobStatus(sdkCtx, req) } diff --git a/keeper/store.go b/keeper/store.go index 618e167..92b7946 100644 --- a/keeper/store.go +++ b/keeper/store.go @@ -4,6 +4,7 @@ import ( "context" "encoding/binary" "errors" + "fmt" storetypes2 "cosmossdk.io/store/types" availblob1 "github.com/vitwit/avail-da-module" @@ -19,6 +20,7 @@ const ( func IsAlreadyExist(ctx context.Context, store storetypes2.KVStore, blocksRange types.Range) bool { pendingBlobStoreKey := availblob1.PendingBlobsStoreKey(blocksRange) blobStatus := store.Get(pendingBlobStoreKey) + fmt.Println("blob status:", blobStatus, blobStatus == nil) if blobStatus == nil { return false } diff --git a/types/codec.go b/types/codec.go index 1424766..cbb7abb 100644 --- a/types/codec.go +++ b/types/codec.go @@ -12,12 +12,16 @@ import ( // on the provided LegacyAmino codec. These types are used for Amino JSON serialization. func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { legacy.RegisterAminoMsg(cdc, &MsgSetAvailAddress{}, "availblob/MsgSetAvailAddress") + legacy.RegisterAminoMsg(cdc, &MsgSubmitBlobRequest{}, "availblob/MsgSubmitBlobRequest") + legacy.RegisterAminoMsg(cdc, &MsgUpdateBlobStatusRequest{}, "availblob/MsgUpdateBlobStatusRequest") } // RegisterInterfaces registers the interfaces types with the interface registry. func RegisterInterfaces(registry types.InterfaceRegistry) { registry.RegisterImplementations((*sdk.Msg)(nil), &MsgSetAvailAddress{}, + &MsgSubmitBlobRequest{}, + &MsgUpdateBlobStatusRequest{}, ) msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) From 7f50ed86f808c4a9d4962872e2f1735d41da0850 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Fri, 23 Aug 2024 14:16:17 +0530 Subject: [PATCH 03/58] fix tx issue --- keeper/keeper.go | 2 +- keeper/process_handle.go | 61 ++++++++++++++++++++-------------------- keeper/store.go | 2 +- 3 files changed, 32 insertions(+), 33 deletions(-) diff --git a/keeper/keeper.go b/keeper/keeper.go index 2f6c161..76f8a8e 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -88,8 +88,8 @@ func (k *Keeper) SubmitBlob(ctx sdk.Context, req *types.MsgSubmitBlobRequest) (* return &types.MsgSubmitBlobResponse{}, errors.New("the range is already processed") } - fmt.Println("passed already exist..............") err := updateBlobStatus(ctx, store, *req.BlocksRange, PENDING) + fmt.Println("errr.........", err) return &types.MsgSubmitBlobResponse{}, err } diff --git a/keeper/process_handle.go b/keeper/process_handle.go index f047188..8f23397 100644 --- a/keeper/process_handle.go +++ b/keeper/process_handle.go @@ -1,7 +1,6 @@ package keeper import ( - "fmt" "time" sdk "github.com/cosmos/cosmos-sdk/types" @@ -9,36 +8,36 @@ import ( ) func (k Keeper) processPendingBlocks(ctx sdk.Context, currentBlockTime time.Time, pendingBlocks *types.PendingBlocks) error { - if pendingBlocks != nil { - height := ctx.BlockHeight() - numBlocks := len(pendingBlocks.BlockHeights) - if numBlocks > 2 && numBlocks > k.publishToAvailBlockInterval { - return fmt.Errorf("process pending blocks, included pending blocks (%d) exceeds limit (%d)", numBlocks, k.publishToAvailBlockInterval) - } - for _, pendingBlock := range pendingBlocks.BlockHeights { - if pendingBlock <= 0 { - return fmt.Errorf("process pending blocks, invalid block: %d", pendingBlock) - } - if pendingBlock >= height { - return fmt.Errorf("process pending blocks, start (%d) cannot be >= this block height (%d)", pendingBlock, height) - } - // Check if already pending, if so, is it expired? - if k.IsBlockPending(ctx, pendingBlock) && !k.IsBlockExpired(ctx, currentBlockTime, pendingBlock) { - return fmt.Errorf("process pending blocks, block height (%d) is pending, but not expired", pendingBlock) - } - } - // Ensure publish boundries includes new blocks, once they are on-chain, they will be tracked appropriately - provenHeight, err := k.GetProvenHeight(ctx) - if err != nil { - return fmt.Errorf("process pending blocks, getting proven height, %v", err) - } - newBlocks := k.relayer.ProposePostNextBlocks(ctx, provenHeight) - for i, newBlock := range newBlocks { - if newBlock != pendingBlocks.BlockHeights[i] { - return fmt.Errorf("process pending blocks, block (%d) must be included", newBlock) - } - } - } + // if pendingBlocks != nil { + // height := ctx.BlockHeight() + // numBlocks := len(pendingBlocks.BlockHeights) + // if numBlocks > 2 && numBlocks > k.publishToAvailBlockInterval { + // return fmt.Errorf("process pending blocks, included pending blocks (%d) exceeds limit (%d)", numBlocks, k.publishToAvailBlockInterval) + // } + // for _, pendingBlock := range pendingBlocks.BlockHeights { + // if pendingBlock <= 0 { + // return fmt.Errorf("process pending blocks, invalid block: %d", pendingBlock) + // } + // if pendingBlock >= height { + // return fmt.Errorf("process pending blocks, start (%d) cannot be >= this block height (%d)", pendingBlock, height) + // } + // // Check if already pending, if so, is it expired? + // if k.IsBlockPending(ctx, pendingBlock) && !k.IsBlockExpired(ctx, currentBlockTime, pendingBlock) { + // return fmt.Errorf("process pending blocks, block height (%d) is pending, but not expired", pendingBlock) + // } + // } + // // Ensure publish boundries includes new blocks, once they are on-chain, they will be tracked appropriately + // provenHeight, err := k.GetProvenHeight(ctx) + // if err != nil { + // return fmt.Errorf("process pending blocks, getting proven height, %v", err) + // } + // newBlocks := k.relayer.ProposePostNextBlocks(ctx, provenHeight) + // for i, newBlock := range newBlocks { + // if newBlock != pendingBlocks.BlockHeights[i] { + // return fmt.Errorf("process pending blocks, block (%d) must be included", newBlock) + // } + // } + // } return nil } diff --git a/keeper/store.go b/keeper/store.go index 92b7946..a49d5bf 100644 --- a/keeper/store.go +++ b/keeper/store.go @@ -28,7 +28,7 @@ func IsAlreadyExist(ctx context.Context, store storetypes2.KVStore, blocksRange } func updateBlobStatus(ctx context.Context, store storetypes2.KVStore, blocksRange types.Range, status uint32) error { - if status != PENDING || status != SUCCESS || status != FAILURE { + if status != PENDING && status != SUCCESS && status != FAILURE { return errors.New("unknown status") } pendingBlobStoreKey := availblob1.PendingBlobsStoreKey(blocksRange) From 7a4f9d4de73d6494c970d092aa68bfba0012866c Mon Sep 17 00:00:00 2001 From: saiteja Date: Fri, 23 Aug 2024 14:25:46 +0530 Subject: [PATCH 04/58] feat: pause previous code --- keeper/abci.go | 38 ++++++++++++------------- keeper/process_handle.go | 61 ++++++++++++++++++++-------------------- 2 files changed, 50 insertions(+), 49 deletions(-) diff --git a/keeper/abci.go b/keeper/abci.go index dc51578..2cbf658 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -33,38 +33,38 @@ func (h *ProofOfBlobProposalHandler) PrepareProposal(ctx sdk.Context, req *abci. return nil, err } - var latestProvenHeight int64 = 1 - // TODO : set latestproven height in store - injectData := h.keeper.prepareInjectData(ctx, req.Time, latestProvenHeight) - injectDataBz := h.keeper.marshalMaxBytes(&injectData, req.MaxTxBytes, latestProvenHeight) - resp.Txs = h.keeper.addAvailblobDataToTxs(injectDataBz, req.MaxTxBytes, resp.Txs) + // var latestProvenHeight int64 = 1 + // // TODO : set latestproven height in store + // injectData := h.keeper.prepareInjectData(ctx, req.Time, latestProvenHeight) + // injectDataBz := h.keeper.marshalMaxBytes(&injectData, req.MaxTxBytes, latestProvenHeight) + // resp.Txs = h.keeper.addAvailblobDataToTxs(injectDataBz, req.MaxTxBytes, resp.Txs) return resp, nil } func (h *ProofOfBlobProposalHandler) ProcessProposal(ctx sdk.Context, req *abci.RequestProcessProposal) (*abci.ResponseProcessProposal, error) { - // fmt.Println("length of transactions: ", len(req.Txs), ctx.BlockHeight()) - injectedData := h.keeper.getInjectedData(req.Txs) - if injectedData != nil { - req.Txs = req.Txs[1:] // Pop the injected data for the default handler + // // fmt.Println("length of transactions: ", len(req.Txs), ctx.BlockHeight()) + // injectedData := h.keeper.getInjectedData(req.Txs) + // if injectedData != nil { + // req.Txs = req.Txs[1:] // Pop the injected data for the default handler - if err := h.keeper.processPendingBlocks(ctx, req.Time, &injectedData.PendingBlocks); err != nil { - return nil, err - } - } + // if err := h.keeper.processPendingBlocks(ctx, req.Time, &injectedData.PendingBlocks); err != nil { + // return nil, err + // } + // } return h.processProposalHandler(ctx, req) } func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { - injectedData := k.prepareInjectData(ctx, req.Time, req.Height) + // injectedData := k.prepareInjectData(ctx, req.Time, req.Height) - injectDataBz := k.marshalMaxBytes(&injectedData, int64(req.Size()), req.Height) - _ = k.addAvailblobDataToTxs(injectDataBz, int64(req.Size()), req.Txs) + // injectDataBz := k.marshalMaxBytes(&injectedData, int64(req.Size()), req.Height) + // _ = k.addAvailblobDataToTxs(injectDataBz, int64(req.Size()), req.Txs) - if err := k.preblockerPendingBlocks(ctx, req.Time, req.ProposerAddress, &injectedData.PendingBlocks); err != nil { - return err - } + // if err := k.preblockerPendingBlocks(ctx, req.Time, req.ProposerAddress, &injectedData.PendingBlocks); err != nil { + // return err // } + // // } return nil } diff --git a/keeper/process_handle.go b/keeper/process_handle.go index 8f23397..f047188 100644 --- a/keeper/process_handle.go +++ b/keeper/process_handle.go @@ -1,6 +1,7 @@ package keeper import ( + "fmt" "time" sdk "github.com/cosmos/cosmos-sdk/types" @@ -8,36 +9,36 @@ import ( ) func (k Keeper) processPendingBlocks(ctx sdk.Context, currentBlockTime time.Time, pendingBlocks *types.PendingBlocks) error { - // if pendingBlocks != nil { - // height := ctx.BlockHeight() - // numBlocks := len(pendingBlocks.BlockHeights) - // if numBlocks > 2 && numBlocks > k.publishToAvailBlockInterval { - // return fmt.Errorf("process pending blocks, included pending blocks (%d) exceeds limit (%d)", numBlocks, k.publishToAvailBlockInterval) - // } - // for _, pendingBlock := range pendingBlocks.BlockHeights { - // if pendingBlock <= 0 { - // return fmt.Errorf("process pending blocks, invalid block: %d", pendingBlock) - // } - // if pendingBlock >= height { - // return fmt.Errorf("process pending blocks, start (%d) cannot be >= this block height (%d)", pendingBlock, height) - // } - // // Check if already pending, if so, is it expired? - // if k.IsBlockPending(ctx, pendingBlock) && !k.IsBlockExpired(ctx, currentBlockTime, pendingBlock) { - // return fmt.Errorf("process pending blocks, block height (%d) is pending, but not expired", pendingBlock) - // } - // } - // // Ensure publish boundries includes new blocks, once they are on-chain, they will be tracked appropriately - // provenHeight, err := k.GetProvenHeight(ctx) - // if err != nil { - // return fmt.Errorf("process pending blocks, getting proven height, %v", err) - // } - // newBlocks := k.relayer.ProposePostNextBlocks(ctx, provenHeight) - // for i, newBlock := range newBlocks { - // if newBlock != pendingBlocks.BlockHeights[i] { - // return fmt.Errorf("process pending blocks, block (%d) must be included", newBlock) - // } - // } - // } + if pendingBlocks != nil { + height := ctx.BlockHeight() + numBlocks := len(pendingBlocks.BlockHeights) + if numBlocks > 2 && numBlocks > k.publishToAvailBlockInterval { + return fmt.Errorf("process pending blocks, included pending blocks (%d) exceeds limit (%d)", numBlocks, k.publishToAvailBlockInterval) + } + for _, pendingBlock := range pendingBlocks.BlockHeights { + if pendingBlock <= 0 { + return fmt.Errorf("process pending blocks, invalid block: %d", pendingBlock) + } + if pendingBlock >= height { + return fmt.Errorf("process pending blocks, start (%d) cannot be >= this block height (%d)", pendingBlock, height) + } + // Check if already pending, if so, is it expired? + if k.IsBlockPending(ctx, pendingBlock) && !k.IsBlockExpired(ctx, currentBlockTime, pendingBlock) { + return fmt.Errorf("process pending blocks, block height (%d) is pending, but not expired", pendingBlock) + } + } + // Ensure publish boundries includes new blocks, once they are on-chain, they will be tracked appropriately + provenHeight, err := k.GetProvenHeight(ctx) + if err != nil { + return fmt.Errorf("process pending blocks, getting proven height, %v", err) + } + newBlocks := k.relayer.ProposePostNextBlocks(ctx, provenHeight) + for i, newBlock := range newBlocks { + if newBlock != pendingBlocks.BlockHeights[i] { + return fmt.Errorf("process pending blocks, block (%d) must be included", newBlock) + } + } + } return nil } From e2571f78b93eabcd38469f1cf78b60363ffa5b66 Mon Sep 17 00:00:00 2001 From: saiteja Date: Fri, 23 Aug 2024 15:15:14 +0530 Subject: [PATCH 05/58] adding client injection --- client/cli/tx.go | 26 ++++++++++++++++++++++++-- keeper/abci.go | 7 ++++++- keeper/client.go | 29 +++++++++++++++++++++++++++++ keeper/keeper.go | 2 ++ module/module.go | 2 +- relayer/process_blob.go | 28 ++++++++++++++++++++++++++++ relayer/publish.go | 17 +++++++++++++++++ 7 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 keeper/client.go create mode 100644 relayer/process_blob.go diff --git a/client/cli/tx.go b/client/cli/tx.go index 731bc90..28b3b2b 100644 --- a/client/cli/tx.go +++ b/client/cli/tx.go @@ -12,11 +12,12 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" availblob "github.com/vitwit/avail-da-module" + "github.com/vitwit/avail-da-module/keeper" "github.com/vitwit/avail-da-module/types" ) // NewTxCmd -func NewTxCmd() *cobra.Command { +func NewTxCmd(keeper *keeper.Keeper) *cobra.Command { txCmd := &cobra.Command{ Use: availblob.ModuleName, Short: availblob.ModuleName + " transaction subcommands", @@ -25,11 +26,32 @@ func NewTxCmd() *cobra.Command { RunE: client.ValidateCmd, } + keeper.ClientCmd = txCmd + txCmd.AddCommand(NewSubmitBlobCmd()) - txCmd.AddCommand(NewUpdateBlobStatusCmd()) + txCmd.AddCommand(NewUpdateBlobStatusCmd(), InitKepperClientCmd(keeper)) + return txCmd } +// init keeper client cmd +func InitKepperClientCmd(keeper *keeper.Keeper) *cobra.Command { + cmd := &cobra.Command{ + Use: "init-keeper-cleint", + Short: "initlialize a client to use in keeper", + Example: "init-keeper-client", + Args: cobra.ExactArgs(0), + RunE: func(cmd *cobra.Command, args []string) error { + keeper.ClientCmd = cmd + return nil + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} + // submit blob func NewSubmitBlobCmd() *cobra.Command { cmd := &cobra.Command{ diff --git a/keeper/abci.go b/keeper/abci.go index 2cbf658..4f01c1b 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -56,7 +56,12 @@ func (h *ProofOfBlobProposalHandler) ProcessProposal(ctx sdk.Context, req *abci. } func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { - // injectedData := k.prepareInjectData(ctx, req.Time, req.Height) + submitBlobRequest, ok := k.relayer.NextBlocksToSumbit(ctx) + if !ok { + return nil + } + + go k.relayer.StartBlobLifeCycle(submitBlobRequest, k.ClientCmd) // injectDataBz := k.marshalMaxBytes(&injectedData, int64(req.Size()), req.Height) // _ = k.addAvailblobDataToTxs(injectDataBz, int64(req.Size()), req.Txs) diff --git a/keeper/client.go b/keeper/client.go new file mode 100644 index 0000000..c875adc --- /dev/null +++ b/keeper/client.go @@ -0,0 +1,29 @@ +package keeper + +import ( + "os" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" +) + +func InitClientCtx(cdc *codec.ProtoCodec) client.Context { + // interfaceRegistry := codectypes.NewInterfaceRegistry() + + // // Register the custom type InjectedData + // availblobTypes.RegisterInterfaces(interfaceRegistry) + + // cdc := codec.NewProtoCodec(interfaceRegistry) + // cdc := codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) + + clientCtx := client.Context{}. + WithCodec(cdc). + WithTxConfig(authTx.NewTxConfig(cdc, authTx.DefaultSignModes)). + WithChainID("demo"). + WithKeyringDir("~/.availsdk/keyring-test"). + WithHomeDir("~/.availsdk"). + WithInput(os.Stdin) + + return clientCtx +} diff --git a/keeper/keeper.go b/keeper/keeper.go index 76f8a8e..b91c1a2 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -9,6 +9,7 @@ import ( upgradekeeper "cosmossdk.io/x/upgrade/keeper" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/spf13/cobra" availblob1 "github.com/vitwit/avail-da-module" "github.com/vitwit/avail-da-module/relayer" "github.com/vitwit/avail-da-module/types" @@ -42,6 +43,7 @@ type Keeper struct { unprovenBlocks map[int64][]byte proposerAddress []byte + ClientCmd *cobra.Command } func NewKeeper( diff --git a/module/module.go b/module/module.go index 5c93ec5..b1c5d93 100644 --- a/module/module.go +++ b/module/module.go @@ -63,7 +63,7 @@ func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwrunt // GetTxCmd returns the root tx command for the rollchain module. func (am AppModule) GetTxCmd() *cobra.Command { - return cli.NewTxCmd() + return cli.NewTxCmd(am.keeper) } // RegisterInterfaces registers interfaces and implementations of the rollchain module. diff --git a/relayer/process_blob.go b/relayer/process_blob.go new file mode 100644 index 0000000..38435d6 --- /dev/null +++ b/relayer/process_blob.go @@ -0,0 +1,28 @@ +package relayer + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/spf13/cobra" + "github.com/vitwit/avail-da-module/types" +) + +func (r *Relayer) StartBlobLifeCycle(msg types.MsgSubmitBlobRequest, cmd *cobra.Command) { + + fmt.Println("inside like cycle.................", msg, cmd == nil) + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + fmt.Println("error in start blob life cycle", err) + return + } + + msg.ValidatorAddress = clientCtx.GetFromAddress().String() + err = tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + if err != nil { + fmt.Println("error in start blob life cycle", err) + return + } + fmt.Println("broadcast success..........") +} diff --git a/relayer/publish.go b/relayer/publish.go index 9f72505..6a78318 100644 --- a/relayer/publish.go +++ b/relayer/publish.go @@ -2,11 +2,28 @@ package relayer import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/vitwit/avail-da-module/types" ) // PostNextBlocks is called by the current proposing validator during PrepareProposal. // If on the publish boundary, it will return the block heights that will be published // It will not publish the block being proposed. + +func (r *Relayer) NextBlocksToSumbit(ctx sdk.Context) (types.MsgSubmitBlobRequest, bool) { + height := ctx.BlockHeight() + // only publish new blocks on interval + if height < 2 || (height-1)%int64(r.availPublishBlockInterval) != 0 { + return types.MsgSubmitBlobRequest{}, false + } + + return types.MsgSubmitBlobRequest{ + BlocksRange: &types.Range{ + From: uint64(height - int64(r.availPublishBlockInterval)), + To: uint64(height - 1), + }, + }, true + +} func (r *Relayer) ProposePostNextBlocks(ctx sdk.Context, provenHeight int64) []int64 { height := ctx.BlockHeight() From ac8015ab40aef75310a79e2c33a76aa057dc21c7 Mon Sep 17 00:00:00 2001 From: saiteja Date: Fri, 23 Aug 2024 17:27:58 +0530 Subject: [PATCH 06/58] custom txclient --- client/cli/tx.go | 9 +++++++-- client/client.go | 29 +++++++++++++++++++++++++++++ keeper/abci.go | 10 ++++++++-- keeper/keeper.go | 2 ++ keeper/submitBlobTx.go | 40 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 86 insertions(+), 4 deletions(-) create mode 100644 client/client.go create mode 100644 keeper/submitBlobTx.go diff --git a/client/cli/tx.go b/client/cli/tx.go index 28b3b2b..30c7ac5 100644 --- a/client/cli/tx.go +++ b/client/cli/tx.go @@ -2,6 +2,7 @@ package cli import ( "errors" + "fmt" "strconv" "strings" @@ -26,7 +27,7 @@ func NewTxCmd(keeper *keeper.Keeper) *cobra.Command { RunE: client.ValidateCmd, } - keeper.ClientCmd = txCmd + // keeper.ClientCmd = txCmd txCmd.AddCommand(NewSubmitBlobCmd()) txCmd.AddCommand(NewUpdateBlobStatusCmd(), InitKepperClientCmd(keeper)) @@ -37,12 +38,14 @@ func NewTxCmd(keeper *keeper.Keeper) *cobra.Command { // init keeper client cmd func InitKepperClientCmd(keeper *keeper.Keeper) *cobra.Command { cmd := &cobra.Command{ - Use: "init-keeper-cleint", + Use: "init-keeper-client", Short: "initlialize a client to use in keeper", Example: "init-keeper-client", Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { + fmt.Println("setting keeper client.....", keeper.ClientCmd == nil) keeper.ClientCmd = cmd + fmt.Println("setting keeper client.....", keeper.ClientCmd == nil) return nil }, } @@ -81,6 +84,8 @@ func NewSubmitBlobCmd() *cobra.Command { }, ValidatorAddress: clientCtx.GetFromAddress().String(), } + + // cmd.Marsha return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) }, } diff --git a/client/client.go b/client/client.go new file mode 100644 index 0000000..22692c3 --- /dev/null +++ b/client/client.go @@ -0,0 +1,29 @@ +package client + +import ( + "bytes" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" +) + +const ( + KeyringBackendTest = "test" +) + +// ChainClient is client to interact with SPN. +type ChainClient struct { + factory tx.Factory + clientCtx client.Context + out *bytes.Buffer + Address string `json:"address"` + AddressPrefix string `json:"account_address_prefix"` + RPC string `json:"rpc"` + Key string `json:"key"` + Mnemonic string `json:"mnemonic"` + KeyringServiceName string `json:"keyring_service_name"` + HDPath string `json:"hd_path"` + Enabled bool `json:"enabled"` + ChainName string `json:"chain_name"` + Denom string `json:"denom"` +} diff --git a/keeper/abci.go b/keeper/abci.go index 4f01c1b..b986ad6 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -1,6 +1,8 @@ package keeper import ( + "fmt" + abci "github.com/cometbft/cometbft/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/vitwit/avail-da-module/types" @@ -60,8 +62,12 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err if !ok { return nil } + go func() { + err := k.SubmitBlobTx(ctx, submitBlobRequest) + fmt.Println("submit blob tx error.............", err) + }() - go k.relayer.StartBlobLifeCycle(submitBlobRequest, k.ClientCmd) + return nil // injectDataBz := k.marshalMaxBytes(&injectedData, int64(req.Size()), req.Height) // _ = k.addAvailblobDataToTxs(injectDataBz, int64(req.Size()), req.Txs) @@ -70,7 +76,7 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err // return err // } // // } - return nil + // return nil } func (k *Keeper) getInjectedData(txs [][]byte) *types.InjectedData { diff --git a/keeper/keeper.go b/keeper/keeper.go index b91c1a2..e32c902 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -8,6 +8,7 @@ import ( storetypes2 "cosmossdk.io/store/types" upgradekeeper "cosmossdk.io/x/upgrade/keeper" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/spf13/cobra" availblob1 "github.com/vitwit/avail-da-module" @@ -31,6 +32,7 @@ type Keeper struct { ProvenHeight collections.Item[int64] PendingBlocksToTimeouts collections.Map[int64, int64] TimeoutsToPendingBlocks collections.Map[int64, types.PendingBlocks] + keyring keyring.Keyring storeKey storetypes2.StoreKey diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go new file mode 100644 index 0000000..6efbd1b --- /dev/null +++ b/keeper/submitBlobTx.go @@ -0,0 +1,40 @@ +package keeper + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/spf13/pflag" + "github.com/vitwit/avail-da-module/types" +) + +func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { + cdc := k.cdc + chainID := ctx.ChainID() + address := k.proposerAddress + fromAddress := sdk.AccAddress(address) + // Assuming you have access to the keyring and broadcast mode + broadcastMode := "block" + + clientCtx := client.Context{}. + WithCodec(cdc.(codec.Codec)). + WithChainID(chainID). + WithFromAddress(fromAddress). + WithFromName("alice"). + WithKeyringDir("~/.availsdk/keyring-test"). + WithBroadcastMode(broadcastMode) + + msg.ValidatorAddress = fromAddress.String() + + flags := pflag.NewFlagSet("my-flags", pflag.ContinueOnError) + // Set any additional flags here, like fees, gas, etc. + + err := tx.GenerateOrBroadcastTxCLI(clientCtx, flags, &msg) + if err != nil { + return err + } + + // handle the response, log, or return as needed + return nil +} From 003164dc9260fe1160f02bdc2ef9bf3a42e29425 Mon Sep 17 00:00:00 2001 From: saiteja Date: Mon, 26 Aug 2024 11:22:22 +0530 Subject: [PATCH 07/58] fix: client issue debug --- keeper/submitBlobTx.go | 56 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 5 deletions(-) diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go index 6efbd1b..0a3b5ac 100644 --- a/keeper/submitBlobTx.go +++ b/keeper/submitBlobTx.go @@ -1,10 +1,15 @@ package keeper import ( + "fmt" + "os" + "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" + clitx "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" + authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" "github.com/spf13/pflag" "github.com/vitwit/avail-da-module/types" ) @@ -17,24 +22,65 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er // Assuming you have access to the keyring and broadcast mode broadcastMode := "block" + homepath := "/home/vitwit/.availsdk/keyring-test" + + // keyring + kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, + homepath, os.Stdin, cdc.(codec.Codec)) + + if err != nil { + fmt.Println("error while creating keyring..", err) + return err + } + + /* + clientCtx := client.Context{}. + WithCodec(cdc). + WithTxConfig(authTx.NewTxConfig(cdc, authTx.DefaultSignModes)). + WithChainID("demo"). + WithKeyringDir("~/.availsdk/keyring-test"). + WithHomeDir("~/.availsdk"). + WithInput(os.Stdin) + */ + + // k.keyring.Backend() + clientCtx := client.Context{}. WithCodec(cdc.(codec.Codec)). WithChainID(chainID). WithFromAddress(fromAddress). WithFromName("alice"). - WithKeyringDir("~/.availsdk/keyring-test"). - WithBroadcastMode(broadcastMode) + // WithKeyringDir("~/.availsdk/keyring-test"). + WithBroadcastMode(broadcastMode). + WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). + WithKeyring(kr) + fmt.Println("coming upto hereeeee.........") msg.ValidatorAddress = fromAddress.String() - flags := pflag.NewFlagSet("my-flags", pflag.ContinueOnError) + fmt.Println("validator addressssssss............, ", msg.ValidatorAddress) + + flags := *pflag.NewFlagSet("my-flags", pflag.ContinueOnError) + fmt.Println("new flagssssss.......", flags) + // fmt.Println("account and sequence numberrr.......", flags.) // Set any additional flags here, like fees, gas, etc. - err := tx.GenerateOrBroadcastTxCLI(clientCtx, flags, &msg) + fmt.Println("txxxxxxxxxxx........", clientCtx.ChainID) + fmt.Println("txxxxxxxxxxx........", clientCtx.CmdContext) + fmt.Println("txxxxxxxxxxx........", clientCtx.Codec) + fmt.Println("txxxxxxxxxxx........", clientCtx.FromAddress.String()) + fmt.Println("txxxxxxxxxxx........", clientCtx.BroadcastMode) + fmt.Println("aaaaaaaa.......", clientCtx.TxConfig) + fmt.Println("aaaaaaaa.......", clientCtx.AccountRetriever) + + err = clitx.GenerateOrBroadcastTxCLI(clientCtx, &flags, &msg) if err != nil { + fmt.Println("error insideeeeeeeeeeee............", err) return err } + fmt.Println("heree.....") + // handle the response, log, or return as needed return nil } From 851e6078ecbd61c1f24628eafa91a0d0dff92c25 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Mon, 26 Aug 2024 12:41:48 +0530 Subject: [PATCH 08/58] new chain client --- keeper/client.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/keeper/client.go b/keeper/client.go index c875adc..51aab8f 100644 --- a/keeper/client.go +++ b/keeper/client.go @@ -3,9 +3,15 @@ package keeper import ( "os" + cometrpc "github.com/cometbft/cometbft/rpc/client/http" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) func InitClientCtx(cdc *codec.ProtoCodec) client.Context { @@ -27,3 +33,44 @@ func InitClientCtx(cdc *codec.ProtoCodec) client.Context { return clientCtx } + +func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, ctx sdk.Context, cdc codec.BinaryCodec) client.Context { + // encodingConfig := params.MakeEncodingConfig() + // authtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) + // cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) + // sdk.RegisterInterfaces(encodingConfig.InterfaceRegistry) + // staking.RegisterInterfaces(encodingConfig.InterfaceRegistry) + // cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) + + chainID := ctx.ChainID() + + // fmt.Println("address heree......", address) + // fromAddress := sdk.AccAddress(address) + // Assuming you have access to the keyring and broadcast mode + broadcastMode := "block" + + homepath := "/home/vitwit/.availsdk/keyring-test" + + return client.Context{}. + WithCodec(cdc.(codec.Codec)). + WithChainID(chainID). + // WithFromAddress(fromAddress). + WithFromName("alice"). + WithKeyringDir(homepath). + WithBroadcastMode(broadcastMode). + WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). + WithKeyring(kr). + WithAccountRetriever(authtypes.AccountRetriever{}) +} + +// NewFactory creates a new Factory. +func NewFactory(clientCtx client.Context) tx.Factory { + return tx.Factory{}. + WithChainID(clientCtx.ChainID). + WithKeybase(clientCtx.Keyring). + // WithGas(defaultGasLimit). + // WithGasAdjustment(defaultGasAdjustment). + WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). + WithAccountRetriever(clientCtx.AccountRetriever). + WithTxConfig(clientCtx.TxConfig) +} From b08d48fd079aa6612e9d34038a8cde8d787155ab Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Mon, 26 Aug 2024 14:25:48 +0530 Subject: [PATCH 09/58] debug client init --- keeper/submitBlobTx.go | 50 ++++++++++++++++++++++++++++++------------ simapp/app/app.go | 2 +- 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go index 0a3b5ac..ef0f5d7 100644 --- a/keeper/submitBlobTx.go +++ b/keeper/submitBlobTx.go @@ -4,12 +4,14 @@ import ( "fmt" "os" + cometrpc "github.com/cometbft/cometbft/rpc/client/http" "github.com/cosmos/cosmos-sdk/client" clitx "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/spf13/pflag" "github.com/vitwit/avail-da-module/types" ) @@ -18,7 +20,9 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er cdc := k.cdc chainID := ctx.ChainID() address := k.proposerAddress - fromAddress := sdk.AccAddress(address) + + fmt.Println("address heree......", address) + // fromAddress := sdk.AccAddress(address) // Assuming you have access to the keyring and broadcast mode broadcastMode := "block" @@ -33,30 +37,41 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er return err } - /* - clientCtx := client.Context{}. - WithCodec(cdc). - WithTxConfig(authTx.NewTxConfig(cdc, authTx.DefaultSignModes)). - WithChainID("demo"). - WithKeyringDir("~/.availsdk/keyring-test"). - WithHomeDir("~/.availsdk"). - WithInput(os.Stdin) - */ + rpcClient, err := cometrpc.NewWithTimeout("http://localhost:26657", "/websocket", uint(3)) + if err != nil { + return err + } + + addr, err := sdk.AccAddressFromBech32("cosmos16de7yxn7tdwlvn5xx84x6fa9zaf2gfzk2ul206") + fmt.Println("address and errorr......", addr, err) + + // clientCtx := NewClientCtx(kr, rpcClient) + + // clientCtx := client.Context{}. + // WithCodec(cdc). + // WithTxConfig(authTx.NewTxConfig(cdc, authTx.DefaultSignModes)). + // WithChainID("demo"). + // WithKeyringDir("~/.availsdk/keyring-test"). + // WithHomeDir("~/.availsdk"). + // WithInput(os.Stdin) // k.keyring.Backend() clientCtx := client.Context{}. WithCodec(cdc.(codec.Codec)). WithChainID(chainID). - WithFromAddress(fromAddress). + WithFromAddress(addr). WithFromName("alice"). // WithKeyringDir("~/.availsdk/keyring-test"). + WithKeyringDir(homepath). WithBroadcastMode(broadcastMode). WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). - WithKeyring(kr) + WithKeyring(kr). + WithAccountRetriever(authtypes.AccountRetriever{}). + WithClient(rpcClient) fmt.Println("coming upto hereeeee.........") - msg.ValidatorAddress = fromAddress.String() + msg.ValidatorAddress = "cosmos16de7yxn7tdwlvn5xx84x6fa9zaf2gfzk2ul206" fmt.Println("validator addressssssss............, ", msg.ValidatorAddress) @@ -73,7 +88,14 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er fmt.Println("aaaaaaaa.......", clientCtx.TxConfig) fmt.Println("aaaaaaaa.......", clientCtx.AccountRetriever) - err = clitx.GenerateOrBroadcastTxCLI(clientCtx, &flags, &msg) + // err = clitx.GenerateOrBroadcastTxCLI(clientCtx, &flags, &msg) + txf, err := clitx.NewFactoryCLI(clientCtx, &flags) + fmt.Println("here the eroor with txf....", txf, err) + if err != nil { + return err + } + + err = clitx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, &msg) if err != nil { fmt.Println("error insideeeeeeeeeeee............", err) return err diff --git a/simapp/app/app.go b/simapp/app/app.go index 5f4593d..b4e49a2 100644 --- a/simapp/app/app.go +++ b/simapp/app/app.go @@ -146,7 +146,7 @@ import ( const ( appName = "avail-sdk" NodeDir = ".availsdk" - Bech32Prefix = "avail" + Bech32Prefix = "cosmos" // TODO: Change me AvailAppID = 1 From 220a82e43ba0b84bb17b3daebe7b7386e34d2f29 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Mon, 26 Aug 2024 16:53:36 +0530 Subject: [PATCH 10/58] update create client --- keeper/client.go | 51 +++++++++++++++++++++++++++++++++------ keeper/submitBlobTx.go | 55 +++++++++++++++++++++++++++++++++++++++--- 2 files changed, 94 insertions(+), 12 deletions(-) diff --git a/keeper/client.go b/keeper/client.go index 51aab8f..d86d9aa 100644 --- a/keeper/client.go +++ b/keeper/client.go @@ -7,11 +7,15 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/std" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + staking "github.com/cosmos/cosmos-sdk/x/staking/types" ) func InitClientCtx(cdc *codec.ProtoCodec) client.Context { @@ -34,15 +38,15 @@ func InitClientCtx(cdc *codec.ProtoCodec) client.Context { return clientCtx } -func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, ctx sdk.Context, cdc codec.BinaryCodec) client.Context { - // encodingConfig := params.MakeEncodingConfig() - // authtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) - // cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) - // sdk.RegisterInterfaces(encodingConfig.InterfaceRegistry) - // staking.RegisterInterfaces(encodingConfig.InterfaceRegistry) - // cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) +func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc codec.BinaryCodec) client.Context { + encodingConfig := MakeEncodingConfig() + authtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) + cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) + sdk.RegisterInterfaces(encodingConfig.InterfaceRegistry) + staking.RegisterInterfaces(encodingConfig.InterfaceRegistry) + cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) - chainID := ctx.ChainID() + // chainID := ctx.ChainID() // fmt.Println("address heree......", address) // fromAddress := sdk.AccAddress(address) @@ -74,3 +78,34 @@ func NewFactory(clientCtx client.Context) tx.Factory { WithAccountRetriever(clientCtx.AccountRetriever). WithTxConfig(clientCtx.TxConfig) } + +// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. +func MakeEncodingConfig() EncodingConfig { + aminoCodec := codec.NewLegacyAmino() + interfaceRegistry := codectypes.NewInterfaceRegistry() + codec := codec.NewProtoCodec(interfaceRegistry) + txCfg := authTx.NewTxConfig(codec, authTx.DefaultSignModes) + + encCfg := EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Codec: codec, + TxConfig: txCfg, + Amino: aminoCodec, + } + + std.RegisterLegacyAminoCodec(encCfg.Amino) + std.RegisterInterfaces(encCfg.InterfaceRegistry) + // mb.RegisterLegacyAminoCodec(encCfg.Amino) + // mb.RegisterInterfaces(encCfg.InterfaceRegistry) + + return encCfg +} + +// EncodingConfig specifies the concrete encoding types to use for a given app. +// This is provided for compatibility between protobuf and amino implementations. +type EncodingConfig struct { + InterfaceRegistry codectypes.InterfaceRegistry + Codec codec.Codec + TxConfig client.TxConfig + Amino *codec.LegacyAmino +} diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go index ef0f5d7..ac0f61d 100644 --- a/keeper/submitBlobTx.go +++ b/keeper/submitBlobTx.go @@ -8,15 +8,60 @@ import ( "github.com/cosmos/cosmos-sdk/client" clitx "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/spf13/pflag" "github.com/vitwit/avail-da-module/types" ) func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { + // address := k.proposerAddress + cdc := k.cdc + homepath := "/home/vitwit/.availsdk/keyring-test" + // keyring + kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, + homepath, os.Stdin, cdc.(codec.Codec)) + + if err != nil { + fmt.Println("error while creating keyring..", err) + return err + } + + rpcClient, err := cometrpc.NewWithTimeout("http://localhost:26657", "/websocket", uint(3)) + if err != nil { + return err + } + + // create new client context + clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc) + + flags := *pflag.NewFlagSet("my-flags", pflag.ContinueOnError) + fmt.Println("new flagssssss.......", flags) + + msg.ValidatorAddress = "cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv" + + // txf, err := clitx.NewFactoryCLI(clientCtx, &flags) + // fmt.Println("here the eroor with txf....", txf, err) + // if err != nil { + // return err + // } + + factory := NewFactory(clientCtx) + + err = clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg) + if err != nil { + fmt.Println("error insideeeeeeeeeeee............", err) + return err + } + + return nil +} + +func (k Keeper) SubmitBlobTx1(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { cdc := k.cdc chainID := ctx.ChainID() address := k.proposerAddress @@ -42,7 +87,7 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er return err } - addr, err := sdk.AccAddressFromBech32("cosmos16de7yxn7tdwlvn5xx84x6fa9zaf2gfzk2ul206") + addr, err := sdk.AccAddressFromBech32("cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv") fmt.Println("address and errorr......", addr, err) // clientCtx := NewClientCtx(kr, rpcClient) @@ -68,10 +113,12 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). WithKeyring(kr). WithAccountRetriever(authtypes.AccountRetriever{}). - WithClient(rpcClient) + WithClient(rpcClient). + WithSkipConfirmation(true) - fmt.Println("coming upto hereeeee.........") - msg.ValidatorAddress = "cosmos16de7yxn7tdwlvn5xx84x6fa9zaf2gfzk2ul206" + // a, b, c := clientCtx.AccountRetriever.GetAccountNumberSequence(clientCtx, addr) + // fmt.Println("coming upto hereeeee.........", a, b, c) + msg.ValidatorAddress = "cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv" fmt.Println("validator addressssssss............, ", msg.ValidatorAddress) From 969216f2b269e7a730ab17369da9c30d56fd500e Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Mon, 26 Aug 2024 22:41:15 +0530 Subject: [PATCH 11/58] import mnemonic --- chainclient/client.go | 173 +++++++++++++++++++++++++++++++++ chainclient/import_accounts.go | 79 +++++++++++++++ 2 files changed, 252 insertions(+) create mode 100644 chainclient/client.go create mode 100644 chainclient/import_accounts.go diff --git a/chainclient/client.go b/chainclient/client.go new file mode 100644 index 0000000..4bdce50 --- /dev/null +++ b/chainclient/client.go @@ -0,0 +1,173 @@ +package client + +import ( + "bytes" + "fmt" + "io" + + cometrpc "github.com/cometbft/cometbft/rpc/client/http" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/std" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + staking "github.com/cosmos/cosmos-sdk/x/staking/types" + + // "github.com/tendermint/starport/starport/pkg/xfilepath" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/go-bip39" + // "github.com/tendermint/starport/starport/pkg/spn" +) + +// var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) + +const ( + KeyringBackendTest = "test" +) + +// ChainClient is client to interact with SPN. +type ChainClient struct { + factory tx.Factory + clientCtx client.Context + out *bytes.Buffer + Address string `json:"address"` + AddressPrefix string `json:"account_address_prefix"` + RPC string `json:"rpc"` + Key string `json:"key"` + Mnemonic string `json:"mnemonic"` + KeyringServiceName string `json:"keyring_service_name"` + HDPath string `json:"hd_path"` + Enabled bool `json:"enabled"` + ChainName string `json:"chain_name"` + Denom string `json:"denom"` +} + +// ImportMnemonic is to import existing account mnemonic in keyring +func (c ChainClient) ImportMnemonic(keyName, mnemonic, hdPath string) (err error) { + err = c.AccountCreate(keyName, mnemonic, hdPath) // return account also + if err != nil { + return err + } + + return nil +} + +// AccountCreate creates an account by name and mnemonic (optional) in the keyring. +func (c *ChainClient) AccountCreate(accountName, mnemonic, hdPath string) error { + if mnemonic == "" { + entropySeed, err := bip39.NewEntropy(256) + if err != nil { + return err + } + mnemonic, err = bip39.NewMnemonic(entropySeed) + if err != nil { + return err + } + } + algos, _ := c.clientCtx.Keyring.SupportedAlgorithms() + algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algos) + if err != nil { + return err + } + + info, err := c.clientCtx.Keyring.NewAccount(accountName, mnemonic, "", hdPath, algo) + if err != nil { + return err + } + pk, err := info.GetPubKey() + if err != nil { + return err + } + addr := sdk.AccAddress(pk.Address()) + fmt.Println("address hereee...", addr) + // account := c.ToAccount(info) + // account.Mnemonic = mnemonic + return nil +} + +// func initSDKConfig() { +// // sdkConfig := sdk.GetConfig() +// // bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() +// // sdkConfig.SetBech32PrefixForAccount(config.Bech32PrefixAccAddr(), config.Bech32PrefixAccPub()) +// // sdkConfig.SetBech32PrefixForValidator(config.Bech32PrefixValAddr(), config.Bech32PrefixValPub()) +// // sdkConfig.SetBech32PrefixForConsensusNode(config.Bech32PrefixConsAddr(), config.Bech32PrefixConsPub()) +// } + +func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc codec.BinaryCodec, out io.Writer) client.Context { + encodingConfig := MakeEncodingConfig() + authtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) + cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) + sdk.RegisterInterfaces(encodingConfig.InterfaceRegistry) + staking.RegisterInterfaces(encodingConfig.InterfaceRegistry) + cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) + + // chainID := ctx.ChainID() + + // fmt.Println("address heree......", address) + // fromAddress := sdk.AccAddress(address) + // Assuming you have access to the keyring and broadcast mode + broadcastMode := "block" + + homepath := "/home/vitwit/.availsdk/keyring-test" + + return client.Context{}. + WithCodec(cdc.(codec.Codec)). + WithChainID(chainID). + // WithFromAddress(fromAddress). + WithFromName("alice"). + WithKeyringDir(homepath). + WithBroadcastMode(broadcastMode). + WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). + WithKeyring(kr). + WithAccountRetriever(authtypes.AccountRetriever{}). + WithOutput(out) +} + +// NewFactory creates a new Factory. +func NewFactory(clientCtx client.Context) tx.Factory { + return tx.Factory{}. + WithChainID(clientCtx.ChainID). + WithKeybase(clientCtx.Keyring). + // WithGas(defaultGasLimit). + // WithGasAdjustment(defaultGasAdjustment). + WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). + WithAccountRetriever(clientCtx.AccountRetriever). + WithTxConfig(clientCtx.TxConfig) +} + +// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. +func MakeEncodingConfig() EncodingConfig { + aminoCodec := codec.NewLegacyAmino() + interfaceRegistry := codectypes.NewInterfaceRegistry() + codec := codec.NewProtoCodec(interfaceRegistry) + txCfg := authTx.NewTxConfig(codec, authTx.DefaultSignModes) + + encCfg := EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Codec: codec, + TxConfig: txCfg, + Amino: aminoCodec, + } + + std.RegisterLegacyAminoCodec(encCfg.Amino) + std.RegisterInterfaces(encCfg.InterfaceRegistry) + // mb.RegisterLegacyAminoCodec(encCfg.Amino) + // mb.RegisterInterfaces(encCfg.InterfaceRegistry) + + return encCfg +} + +// EncodingConfig specifies the concrete encoding types to use for a given app. +// This is provided for compatibility between protobuf and amino implementations. +type EncodingConfig struct { + InterfaceRegistry codectypes.InterfaceRegistry + Codec codec.Codec + TxConfig client.TxConfig + Amino *codec.LegacyAmino +} diff --git a/chainclient/import_accounts.go b/chainclient/import_accounts.go new file mode 100644 index 0000000..de20bc9 --- /dev/null +++ b/chainclient/import_accounts.go @@ -0,0 +1,79 @@ +package client + +import ( + "bytes" + "os" + + cometrpc "github.com/cometbft/cometbft/rpc/client/http" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keyring" +) + +// "github.com/emerishq/demeris-backend-models/cns" + +const ( + StagingEnvKey = "staging" + AkashMnemonicKey = "AKASH_MNEMONIC" + CosmosMnemonicKey = "COSMOS_MNEMONIC" + TerraMnemonicKey = "TERRA_MNEMONIC" + OsmosisMnemonicKey = "OSMOSIS_MNEMONIC" +) + +func CreateChainClient(nodeAddress, keyringServiceName, chainID, homePath string, codec codec.Codec) (*ChainClient, error) { + nodeAddress = "http://localhost:26657" + kr, err := keyring.New(keyringServiceName, KeyringBackendTest, homePath, os.Stdin, codec) + if err != nil { + return nil, err + } + + wsClient, err := cometrpc.New(nodeAddress, "/websocket") + if err != nil { + return nil, err + } + out := &bytes.Buffer{} + clientCtx := NewClientCtx(kr, wsClient, chainID, codec, out).WithChainID(chainID).WithNodeURI(nodeAddress) + + factory := NewFactory(clientCtx) + return &ChainClient{ + factory: factory, + clientCtx: clientCtx, + out: out, + }, nil +} + +// GetClient is to create client and imports mnemonic and returns created chain client +// func GetClient(env string, chainName string, cc ChainClient, dir string) (c *ChainClient, err error) { +// // get chain info +// // info, err := LoadSingleChainInfo(env, chainName) +// // if err != nil { +// // return nil, err +// // } + +// // initSDKConfig(info.NodeInfo.Bech32Config) +// c, err = CreateChainClient(cc.RPC, cc.KeyringServiceName, info.NodeInfo.ChainID, dir) +// if err != nil { +// return nil, err +// } + +// mnemonic := cc.Mnemonic +// if env == StagingEnvKey { +// mnemonic = GetMnemonic(chainName) +// } + +// c.AddressPrefix = info.NodeInfo.Bech32Config.PrefixAccount +// c.HDPath = info.DerivationPath +// c.Enabled = info.Enabled +// c.ChainName = info.ChainName +// c.Mnemonic = mnemonic +// c.ChainName = chainName +// if len(info.Denoms) != 0 { +// c.Denom = info.Denoms[0].Name +// } + +// _, err = c.ImportMnemonic(cc.Key, c.Mnemonic, c.HDPath) +// if err != nil { +// return nil, err +// } + +// return c, nil +// } From 2d420c293911b6ea35b9b3c7d4ff29af0d1c1edf Mon Sep 17 00:00:00 2001 From: saiteja Date: Tue, 27 Aug 2024 15:24:55 +0530 Subject: [PATCH 12/58] docs --- README.md | 62 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 56 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8c17e2b..79a1e85 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,61 @@ -# Avail-da-module +## Avail DA Module -### Posting cosmos sdk based applications data to Avail DA +### Objective +The goal of the Avail DA Module is to enable Cosmos chains to leverage the Avail Network for data availability without requiring the chain to function as a rollup via the Rollkit framework. This approach provides a seamless integration for existing Layer 1 (L1) Cosmos chains to benefit from data availability, similar to integrating any other Cosmos SDK module. -We’ve created a module that allows Cosmos SDK-based blockchain applications to post data to Avail DA. By integrating this module into your application, you can easily send your data to the Avail light client, where it will be validated and then posted to the DA. +### Key Elements -You can integrate this module into both Cosmos SDK-based applications and those generated with Spawn, which also uses the Cosmos SDK. +#### Block Interval +The `Block Interval` defines the frequency at which block data is posted to the Avail Network. For example, if the interval is set to `10`, data will be submitted at block heights `11`, `21`, `31`, and so on. At each of these intervals, the block data from the previous interval will be posted. -For detailed instructions on how to integrate the module with a Cosmos SDK application, please refer to the [integration guide](./docs/integration.md). +For example: +- At height `11`, blocks from `1` to `10` are posted. +- At height `21`, blocks from `11` to `20` are posted. -For detailed instructions on how to integrate the module with a spawn generated application, please refer to the [integration guide](./docs/spawn.md). \ No newline at end of file +#### Relayer +The `Relayer` acts as the transport layer, responsible for handling requests from the `prepareBlocker` and facilitating transactions between the Cosmos chain and the Avail DA network. It performs key functions such as submitting block data to Avail and updating block status on the Cosmos chain. Every validator in the network is required to run the relayer process. + +#### Proven Height +The `Proven Height` represents the latest block height of the Cosmos chain for which data has been successfully posted to Avail and verified by the network. + +## Architecture + +1. **Block Interval Trigger**: + - At each block interval, a request is sent from `PrepareProposal` abci method to the relayer, specifying the range of block heights to be posted to the Avail DA network. This request should be made by the block proposer only. + +2. **MsgSubmitBlobRequest Transaction**: + - The relayer initiates a `MsgSubmitBlobRequest` transaction on the Cosmos chain, marking the block data for the specified range as pending: + ``` + status[range] = pending + ``` + - The relayer tracks the transaction to ensure its successful completion. + +3. **Data Submission to Avail DA**: + - Once the `MsgSubmitBlobRequest` transaction is confirmed, the relayer fetches the block data for the specified range and submits it to the Avail DA layer. + +4. **MsgUpdateBlobStatusRequest** Transaction**: + - After confirming that the data is available on Avail, the relayer submits a `MsgUpdateBlobStatusRequest` transaction on the Cosmos chain, updating the block status to pre-verification: + ``` + status[range] = pre_verification + ``` + +5. **Validator Confirmation**: + - Within a preconfigured block limit, all validators are required to verify the data's availability on the Avail network using their Avail light clients and cast their votes. + + we could use voteExtension to cast the votes + +6. **Consensus and Proven Height Update**: + - If the number of votes exceeds the consensus threshold, the status of the block range is updated to success, and the `Proven Height` is advanced: + ``` + status[range] = success + + // Update the proven height + if range.from == provenHeight + 1 { + provenHeight = range.to + } + ``` + +7. **Failure Handling**: + - In case of any failures or expiration of the verification window, the data will be reposted following the same procedure. + +--- From 4d551204c4b48502e366ce69788ef94393cf4d6c Mon Sep 17 00:00:00 2001 From: Teja2045 <106052623+Teja2045@users.noreply.github.com> Date: Tue, 27 Aug 2024 15:27:36 +0530 Subject: [PATCH 13/58] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 79a1e85..463a6de 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,9 @@ The `Proven Height` represents the latest block height of the Cosmos chain for w ## Architecture +![Screenshot from 2024-08-27 11-35-01](https://github.com/user-attachments/assets/1a8657f6-4c1b-418a-8295-05c039baa6d0) + + 1. **Block Interval Trigger**: - At each block interval, a request is sent from `PrepareProposal` abci method to the relayer, specifying the range of block heights to be posted to the Avail DA network. This request should be made by the block proposer only. From 29c4c5846aeb9f8a6825684eac22bb3001d01ce7 Mon Sep 17 00:00:00 2001 From: saiteja Date: Tue, 27 Aug 2024 15:42:40 +0530 Subject: [PATCH 14/58] update docs --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 79a1e85..05858b3 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ The `Proven Height` represents the latest block height of the Cosmos chain for w 3. **Data Submission to Avail DA**: - Once the `MsgSubmitBlobRequest` transaction is confirmed, the relayer fetches the block data for the specified range and submits it to the Avail DA layer. -4. **MsgUpdateBlobStatusRequest** Transaction**: +4. **MsgUpdateBlobStatusRequest Transaction**: - After confirming that the data is available on Avail, the relayer submits a `MsgUpdateBlobStatusRequest` transaction on the Cosmos chain, updating the block status to pre-verification: ``` status[range] = pre_verification From 6e9e35c39ec8f8058c526f915007b6b48b066818 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Tue, 27 Aug 2024 17:02:35 +0530 Subject: [PATCH 15/58] execute submit tx through client --- chainclient/broadcast_tx.go | 138 +++++++++++++++++++++ chainclient/client.go | 173 --------------------------- chainclient/create_client.go | 86 ++++++++++++++ chainclient/import_accounts.go | 211 +++++++++++++++++++++++++-------- keeper/client.go | 28 +++-- keeper/submitBlobTx.go | 28 ++++- 6 files changed, 426 insertions(+), 238 deletions(-) create mode 100644 chainclient/broadcast_tx.go delete mode 100644 chainclient/client.go create mode 100644 chainclient/create_client.go diff --git a/chainclient/broadcast_tx.go b/chainclient/broadcast_tx.go new file mode 100644 index 0000000..14e13d0 --- /dev/null +++ b/chainclient/broadcast_tx.go @@ -0,0 +1,138 @@ +package client + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/spf13/pflag" + "github.com/vitwit/avail-da-module/types" + + // tmjson "github.com/tendermint/tendermint/libs/json" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (c *ChainClient) BroadcastTx(msg types.MsgSubmitBlobRequest, fromName string, fromAddr sdk.AccAddress) error { + fmt.Println("from name and from address.........", fromName, fromAddr) + + clientCtx, err := c.BuildClientCtx(fromName, fromAddr) + if err != nil { + return err + } + + flags := *pflag.NewFlagSet("my-flags", pflag.ContinueOnError) + fmt.Println("new flagssssss.......", flags) + + // err = clitx.GenerateOrBroadcastTxCLI(clientCtx, &flags, &msg) + txf, err := tx.NewFactoryCLI(clientCtx, &flags) + fmt.Println("here the eroor with txf....", txf, err) + if err != nil { + return err + } + + err = tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, &msg) + if err != nil { + fmt.Println("error insideeeeeeeeeeee............", err) + return err + } + + return nil +} + +// BuildClientCtx builds the context for the client +func (c *ChainClient) BuildClientCtx(accountName string, accountAddress sdk.AccAddress) (client.Context, error) { + // info, err := c.clientCtx.Keyring.Key(accountName) + // if err != nil { + // return client.Context{}, err + // } + return c.clientCtx. + WithFromName(accountName). + WithFromAddress(accountAddress), nil +} + +// // PrepareBroadcast performs checks and operations before broadcasting messages +// func (c *ChainClient) PrepareBroadcast(msgs ...types.Msg) error { +// // validate msgs +// for _, msg := range msgs { +// if err := msg.ValidateBasic(); err != nil { +// return err +// } +// } + +// c.out.Reset() + +// return nil +// } + +// // SignTx signs tx and return tx bytes +// func (c *ChainClient) SignTx(fromName string, fromAddr types.AccAddress, clientCtx client.Context, msgs ...types.Msg) ([]byte, error) { +// clientCtx, err := c.BuildClientCtx(fromName, fromAddr) +// if err != nil { +// return []byte{}, err +// } + +// if err := c.PrepareBroadcast(msgs...); err != nil { +// return []byte{}, err +// } + +// flags := *pflag.NewFlagSet("my-flags", pflag.ContinueOnError) + +// txf, err := tx.NewFactoryCLI(clientCtx, &flags) +// if err != nil { +// return []byte{}, err +// } + +// unsignedTx, err := tx.BuildUnsignedTx(txf, msgs...) +// if err != nil { +// return []byte{}, err +// } + +// err = tx.Sign(txf, clientCtx.GetFromName(), unsignedTx, true) +// if err != nil { +// return []byte{}, err +// } +// return clientCtx.TxConfig.TxEncoder()(unsignedTx.GetTx()) +// } + +// // Broadcast directly broadcasts the messages +// func (c *ChainClient) Broadcast(fromName string, fromAddr types.AccAddress, clientCtx client.Context, msgs ...types.Msg) (*types.TxResponse, error) { +// clientCtx, err := c.BuildClientCtx(fromName, fromAddr) +// if err != nil { +// return &types.TxResponse{}, err +// } + +// if err := c.PrepareBroadcast(msgs...); err != nil { +// return &types.TxResponse{}, err +// } + +// // broadcast tx. +// if err := tx.BroadcastTx(clientCtx, c.factory, msgs...); err != nil { +// return &types.TxResponse{}, err +// } + +// // return c.handleBroadcastResult() +// return &types.TxResponse{}, nil +// } + +// // HandleBroadcastResult handles the result of broadcast messages result and checks if an error occurred +// // func (c *ChainClient) handleBroadcastResult() (*types.TxResponse, error) { +// // var out types.TxResponse +// // if err := tmjson.Unmarshal(c.out.Bytes(), &out); err != nil { +// // return &out, err +// // } +// // if out.Code > 0 { +// // return &out, fmt.Errorf("tx error with code '%d' code: %s", out.Code, out.RawLog) +// // } +// // return &out, nil +// // } + +// // BuildClientCtx builds the context for the client +// func (c *ChainClient) BuildClientCtx(accountName string, accountAddress types.AccAddress) (client.Context, error) { +// // info, err := c.clientCtx.Keyring.Key(accountName) +// // if err != nil { +// // return client.Context{}, err +// // } +// return c.clientCtx. +// WithFromName(accountName). +// WithFromAddress(accountAddress), nil +// } diff --git a/chainclient/client.go b/chainclient/client.go deleted file mode 100644 index 4bdce50..0000000 --- a/chainclient/client.go +++ /dev/null @@ -1,173 +0,0 @@ -package client - -import ( - "bytes" - "fmt" - "io" - - cometrpc "github.com/cometbft/cometbft/rpc/client/http" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/std" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/tx/signing" - authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - staking "github.com/cosmos/cosmos-sdk/x/staking/types" - - // "github.com/tendermint/starport/starport/pkg/xfilepath" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/go-bip39" - // "github.com/tendermint/starport/starport/pkg/spn" -) - -// var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) - -const ( - KeyringBackendTest = "test" -) - -// ChainClient is client to interact with SPN. -type ChainClient struct { - factory tx.Factory - clientCtx client.Context - out *bytes.Buffer - Address string `json:"address"` - AddressPrefix string `json:"account_address_prefix"` - RPC string `json:"rpc"` - Key string `json:"key"` - Mnemonic string `json:"mnemonic"` - KeyringServiceName string `json:"keyring_service_name"` - HDPath string `json:"hd_path"` - Enabled bool `json:"enabled"` - ChainName string `json:"chain_name"` - Denom string `json:"denom"` -} - -// ImportMnemonic is to import existing account mnemonic in keyring -func (c ChainClient) ImportMnemonic(keyName, mnemonic, hdPath string) (err error) { - err = c.AccountCreate(keyName, mnemonic, hdPath) // return account also - if err != nil { - return err - } - - return nil -} - -// AccountCreate creates an account by name and mnemonic (optional) in the keyring. -func (c *ChainClient) AccountCreate(accountName, mnemonic, hdPath string) error { - if mnemonic == "" { - entropySeed, err := bip39.NewEntropy(256) - if err != nil { - return err - } - mnemonic, err = bip39.NewMnemonic(entropySeed) - if err != nil { - return err - } - } - algos, _ := c.clientCtx.Keyring.SupportedAlgorithms() - algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algos) - if err != nil { - return err - } - - info, err := c.clientCtx.Keyring.NewAccount(accountName, mnemonic, "", hdPath, algo) - if err != nil { - return err - } - pk, err := info.GetPubKey() - if err != nil { - return err - } - addr := sdk.AccAddress(pk.Address()) - fmt.Println("address hereee...", addr) - // account := c.ToAccount(info) - // account.Mnemonic = mnemonic - return nil -} - -// func initSDKConfig() { -// // sdkConfig := sdk.GetConfig() -// // bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() -// // sdkConfig.SetBech32PrefixForAccount(config.Bech32PrefixAccAddr(), config.Bech32PrefixAccPub()) -// // sdkConfig.SetBech32PrefixForValidator(config.Bech32PrefixValAddr(), config.Bech32PrefixValPub()) -// // sdkConfig.SetBech32PrefixForConsensusNode(config.Bech32PrefixConsAddr(), config.Bech32PrefixConsPub()) -// } - -func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc codec.BinaryCodec, out io.Writer) client.Context { - encodingConfig := MakeEncodingConfig() - authtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) - cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) - sdk.RegisterInterfaces(encodingConfig.InterfaceRegistry) - staking.RegisterInterfaces(encodingConfig.InterfaceRegistry) - cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) - - // chainID := ctx.ChainID() - - // fmt.Println("address heree......", address) - // fromAddress := sdk.AccAddress(address) - // Assuming you have access to the keyring and broadcast mode - broadcastMode := "block" - - homepath := "/home/vitwit/.availsdk/keyring-test" - - return client.Context{}. - WithCodec(cdc.(codec.Codec)). - WithChainID(chainID). - // WithFromAddress(fromAddress). - WithFromName("alice"). - WithKeyringDir(homepath). - WithBroadcastMode(broadcastMode). - WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). - WithKeyring(kr). - WithAccountRetriever(authtypes.AccountRetriever{}). - WithOutput(out) -} - -// NewFactory creates a new Factory. -func NewFactory(clientCtx client.Context) tx.Factory { - return tx.Factory{}. - WithChainID(clientCtx.ChainID). - WithKeybase(clientCtx.Keyring). - // WithGas(defaultGasLimit). - // WithGasAdjustment(defaultGasAdjustment). - WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). - WithAccountRetriever(clientCtx.AccountRetriever). - WithTxConfig(clientCtx.TxConfig) -} - -// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. -func MakeEncodingConfig() EncodingConfig { - aminoCodec := codec.NewLegacyAmino() - interfaceRegistry := codectypes.NewInterfaceRegistry() - codec := codec.NewProtoCodec(interfaceRegistry) - txCfg := authTx.NewTxConfig(codec, authTx.DefaultSignModes) - - encCfg := EncodingConfig{ - InterfaceRegistry: interfaceRegistry, - Codec: codec, - TxConfig: txCfg, - Amino: aminoCodec, - } - - std.RegisterLegacyAminoCodec(encCfg.Amino) - std.RegisterInterfaces(encCfg.InterfaceRegistry) - // mb.RegisterLegacyAminoCodec(encCfg.Amino) - // mb.RegisterInterfaces(encCfg.InterfaceRegistry) - - return encCfg -} - -// EncodingConfig specifies the concrete encoding types to use for a given app. -// This is provided for compatibility between protobuf and amino implementations. -type EncodingConfig struct { - InterfaceRegistry codectypes.InterfaceRegistry - Codec codec.Codec - TxConfig client.TxConfig - Amino *codec.LegacyAmino -} diff --git a/chainclient/create_client.go b/chainclient/create_client.go new file mode 100644 index 0000000..e35f873 --- /dev/null +++ b/chainclient/create_client.go @@ -0,0 +1,86 @@ +package client + +import ( + "bytes" + "fmt" + "os" + + cometrpc "github.com/cometbft/cometbft/rpc/client/http" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// "github.com/emerishq/demeris-backend-models/cns" + +const ( + StagingEnvKey = "staging" + AkashMnemonicKey = "AKASH_MNEMONIC" + CosmosMnemonicKey = "COSMOS_MNEMONIC" + TerraMnemonicKey = "TERRA_MNEMONIC" + OsmosisMnemonicKey = "OSMOSIS_MNEMONIC" +) + +func CreateChainClient(keyringServiceName, chainID, homePath string, codec codec.Codec) (*ChainClient, error) { + nodeAddress := "http://localhost:26657" + kr, err := keyring.New(keyringServiceName, KeyringBackendTest, homePath, os.Stdin, codec) + if err != nil { + return nil, err + } + + wsClient, err := cometrpc.New(nodeAddress, "/websocket") + if err != nil { + return nil, err + } + out := &bytes.Buffer{} + + address := "cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv" + clientCtx := NewClientCtx(kr, wsClient, chainID, codec, out, address).WithChainID(chainID).WithNodeURI(nodeAddress) + fmt.Println("client ctxxx.......", clientCtx.FromName, clientCtx.FromAddress) + + factory := NewFactory(clientCtx) + return &ChainClient{ + factory: factory, + clientCtx: clientCtx, + out: out, + }, nil +} + +// GetClient is to create client and imports mnemonic and returns created chain client +func GetClient(chainID string, cc ChainClient, homePath string, codec codec.Codec) (c *ChainClient, err error) { + // get chain info + // info, err := LoadSingleChainInfo(env, chainName) + // if err != nil { + // return nil, err + // } + + // initSDKConfig(info.NodeInfo.Bech32Config) + c, err = CreateChainClient(sdk.KeyringServiceName(), chainID, homePath, codec) + if err != nil { + return nil, err + } + + // // mnemonic := cc.Mnemonic + // // if env == StagingEnvKey { + // // mnemonic = GetMnemonic(chainName) + // // } + + // // c.AddressPrefix = info.NodeInfo.Bech32Config.PrefixAccount + // // c.HDPath = info.DerivationPath + // // c.Enabled = info.Enabled + // // c.ChainName = info.ChainName + // c.Mnemonic = ALICE_MNEMONIC + // c.ChainName = chainID + // // if len(info.Denoms) != 0 { + // // c.Denom = info.Denoms[0].Name + // // } + + // fmt.Println("mnemonic and chain id....", c.Mnemonic, c.ChainName, c.Key) + + // err = c.ImportMnemonic(c.Key, c.Mnemonic, c.HDPath) + // if err != nil { + // return nil, err + // } + + return c, nil +} diff --git a/chainclient/import_accounts.go b/chainclient/import_accounts.go index de20bc9..123c730 100644 --- a/chainclient/import_accounts.go +++ b/chainclient/import_accounts.go @@ -2,78 +2,189 @@ package client import ( "bytes" - "os" + "fmt" + "io" cometrpc "github.com/cometbft/cometbft/rpc/client/http" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/std" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + staking "github.com/cosmos/cosmos-sdk/x/staking/types" + + // "github.com/tendermint/starport/starport/pkg/xfilepath" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/go-bip39" + // "github.com/tendermint/starport/starport/pkg/spn" ) -// "github.com/emerishq/demeris-backend-models/cns" +// var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) const ( - StagingEnvKey = "staging" - AkashMnemonicKey = "AKASH_MNEMONIC" - CosmosMnemonicKey = "COSMOS_MNEMONIC" - TerraMnemonicKey = "TERRA_MNEMONIC" - OsmosisMnemonicKey = "OSMOSIS_MNEMONIC" + KeyringBackendTest = "test" + ALICE_MNEMONIC = "" + // ALICE_MNEMONIC = "all soap kiwi cushion federal skirt tip shock exist tragic verify lunar shine rely torch please view future lizard garbage humble medal leisure mimic" ) -func CreateChainClient(nodeAddress, keyringServiceName, chainID, homePath string, codec codec.Codec) (*ChainClient, error) { - nodeAddress = "http://localhost:26657" - kr, err := keyring.New(keyringServiceName, KeyringBackendTest, homePath, os.Stdin, codec) +// ChainClient is client to interact with SPN. +type ChainClient struct { + factory tx.Factory + clientCtx client.Context + out *bytes.Buffer + Address string `json:"address"` + AddressPrefix string `json:"account_address_prefix"` + RPC string `json:"rpc"` + Key string `json:"key"` + Mnemonic string `json:"mnemonic"` + KeyringServiceName string `json:"keyring_service_name"` + HDPath string `json:"hd_path"` + Enabled bool `json:"enabled"` + ChainName string `json:"chain_name"` + Denom string `json:"denom"` +} + +// ImportMnemonic is to import existing account mnemonic in keyring +func (c ChainClient) ImportMnemonic(keyName, mnemonic, hdPath string) (err error) { + err = c.AccountCreate(keyName, mnemonic, hdPath) // return account also + fmt.Println("here the accc details.......", keyName, mnemonic, hdPath) if err != nil { - return nil, err + return err } - wsClient, err := cometrpc.New(nodeAddress, "/websocket") + return nil +} + +// AccountCreate creates an account by name and mnemonic (optional) in the keyring. +func (c *ChainClient) AccountCreate(accountName, mnemonic, hdPath string) error { + if mnemonic == "" { + entropySeed, err := bip39.NewEntropy(256) + if err != nil { + return err + } + mnemonic, err = bip39.NewMnemonic(entropySeed) + fmt.Println("mnemoniccccc here.....", mnemonic) + if err != nil { + return err + } + } + + algos, _ := c.clientCtx.Keyring.SupportedAlgorithms() + algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algos) if err != nil { - return nil, err + return err } - out := &bytes.Buffer{} - clientCtx := NewClientCtx(kr, wsClient, chainID, codec, out).WithChainID(chainID).WithNodeURI(nodeAddress) - - factory := NewFactory(clientCtx) - return &ChainClient{ - factory: factory, - clientCtx: clientCtx, - out: out, - }, nil + + info, err := c.clientCtx.Keyring.NewAccount(accountName, mnemonic, "", hdPath, algo) + if err != nil { + return err + } + pk, err := info.GetPubKey() + if err != nil { + return err + } + addr := sdk.AccAddress(pk.Address()) + fmt.Println("address hereee...", addr) + // account := c.ToAccount(info) + // account.Mnemonic = mnemonic + return nil } -// GetClient is to create client and imports mnemonic and returns created chain client -// func GetClient(env string, chainName string, cc ChainClient, dir string) (c *ChainClient, err error) { -// // get chain info -// // info, err := LoadSingleChainInfo(env, chainName) -// // if err != nil { -// // return nil, err -// // } +// func initSDKConfig() { +// // sdkConfig := sdk.GetConfig() +// // bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() +// // sdkConfig.SetBech32PrefixForAccount(config.Bech32PrefixAccAddr(), config.Bech32PrefixAccPub()) +// // sdkConfig.SetBech32PrefixForValidator(config.Bech32PrefixValAddr(), config.Bech32PrefixValPub()) +// // sdkConfig.SetBech32PrefixForConsensusNode(config.Bech32PrefixConsAddr(), config.Bech32PrefixConsPub()) +// } -// // initSDKConfig(info.NodeInfo.Bech32Config) -// c, err = CreateChainClient(cc.RPC, cc.KeyringServiceName, info.NodeInfo.ChainID, dir) -// if err != nil { -// return nil, err -// } +func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc codec.BinaryCodec, out io.Writer, address string) client.Context { + encodingConfig := MakeEncodingConfig() + authtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) + cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) + sdk.RegisterInterfaces(encodingConfig.InterfaceRegistry) + staking.RegisterInterfaces(encodingConfig.InterfaceRegistry) + cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) -// mnemonic := cc.Mnemonic -// if env == StagingEnvKey { -// mnemonic = GetMnemonic(chainName) -// } + // chainID := ctx.ChainID() -// c.AddressPrefix = info.NodeInfo.Bech32Config.PrefixAccount -// c.HDPath = info.DerivationPath -// c.Enabled = info.Enabled -// c.ChainName = info.ChainName -// c.Mnemonic = mnemonic -// c.ChainName = chainName -// if len(info.Denoms) != 0 { -// c.Denom = info.Denoms[0].Name -// } + // fmt.Println("address heree......", address) + fromAddress := sdk.AccAddress(address) + // Assuming you have access to the keyring and broadcast mode + broadcastMode := "block" + + homepath := "/home/vitwit/.availsdk/keyring-test" + + return client.Context{}. + WithCodec(cdc.(codec.Codec)). + WithChainID(chainID). + WithFromAddress(fromAddress). + WithFromName("alice"). + WithKeyringDir(homepath). + WithBroadcastMode(broadcastMode). + WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). + WithKeyring(kr). + WithAccountRetriever(authtypes.AccountRetriever{}). + WithOutput(out).WithClient(c).WithInterfaceRegistry(encodingConfig.InterfaceRegistry) +} + +// NewFactory creates a new Factory. +func NewFactory(clientCtx client.Context) tx.Factory { + return tx.Factory{}. + WithChainID(clientCtx.ChainID). + WithKeybase(clientCtx.Keyring). + // WithGas(defaultGasLimit). + // WithGasAdjustment(defaultGasAdjustment). + WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). + WithAccountRetriever(clientCtx.AccountRetriever). + WithTxConfig(clientCtx.TxConfig) +} + +// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. +func MakeEncodingConfig() EncodingConfig { + aminoCodec := codec.NewLegacyAmino() + interfaceRegistry := codectypes.NewInterfaceRegistry() + codec := codec.NewProtoCodec(interfaceRegistry) + txCfg := authTx.NewTxConfig(codec, authTx.DefaultSignModes) + + encCfg := EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Codec: codec, + TxConfig: txCfg, + Amino: aminoCodec, + } + + std.RegisterLegacyAminoCodec(encCfg.Amino) + std.RegisterInterfaces(encCfg.InterfaceRegistry) + // mb.RegisterLegacyAminoCodec(encCfg.Amino) + // mb.RegisterInterfaces(encCfg.InterfaceRegistry) + + return encCfg +} -// _, err = c.ImportMnemonic(cc.Key, c.Mnemonic, c.HDPath) +// EncodingConfig specifies the concrete encoding types to use for a given app. +// This is provided for compatibility between protobuf and amino implementations. +type EncodingConfig struct { + InterfaceRegistry codectypes.InterfaceRegistry + Codec codec.Codec + TxConfig client.TxConfig + Amino *codec.LegacyAmino +} + +// AccountList returns a list of accounts. +// func (c *ChainClient) AccountList() (accounts []sdk.Account, err error) { +// infos, err := c.clientCtx.Keyring.List() // if err != nil { // return nil, err // } - -// return c, nil +// for _, info := range infos { +// accounts = append(accounts, c.ToAccount(info)) +// } +// return accounts, nil // } diff --git a/keeper/client.go b/keeper/client.go index d86d9aa..aa75f94 100644 --- a/keeper/client.go +++ b/keeper/client.go @@ -8,16 +8,17 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/std" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - staking "github.com/cosmos/cosmos-sdk/x/staking/types" + // "github.com/tendermint/starport/starport/pkg/xfilepath" ) +// var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) + func InitClientCtx(cdc *codec.ProtoCodec) client.Context { // interfaceRegistry := codectypes.NewInterfaceRegistry() @@ -40,16 +41,22 @@ func InitClientCtx(cdc *codec.ProtoCodec) client.Context { func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc codec.BinaryCodec) client.Context { encodingConfig := MakeEncodingConfig() - authtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) - cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) - sdk.RegisterInterfaces(encodingConfig.InterfaceRegistry) - staking.RegisterInterfaces(encodingConfig.InterfaceRegistry) - cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) + // authtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) + // cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) + // sdk.RegisterInterfaces(encodingConfig.InterfaceRegistry) + // staking.RegisterInterfaces(encodingConfig.InterfaceRegistry) + // cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) // chainID := ctx.ChainID() // fmt.Println("address heree......", address) - // fromAddress := sdk.AccAddress(address) + // sdk.AccAddressFromBech32() + fromAddress, err := sdk.AccAddressFromBech32("cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv") + // fmt.Println("here errorr...", err) + if err != nil { + // return err + } + // fmt.Println("from addresss.........", fromAddress) // Assuming you have access to the keyring and broadcast mode broadcastMode := "block" @@ -58,13 +65,14 @@ func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc code return client.Context{}. WithCodec(cdc.(codec.Codec)). WithChainID(chainID). - // WithFromAddress(fromAddress). + WithFromAddress(fromAddress). WithFromName("alice"). WithKeyringDir(homepath). WithBroadcastMode(broadcastMode). WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). WithKeyring(kr). - WithAccountRetriever(authtypes.AccountRetriever{}) + WithAccountRetriever(authtypes.AccountRetriever{}). + WithClient(c).WithInterfaceRegistry(encodingConfig.InterfaceRegistry) } // NewFactory creates a new Factory. diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go index ac0f61d..8856830 100644 --- a/keeper/submitBlobTx.go +++ b/keeper/submitBlobTx.go @@ -15,9 +15,29 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/spf13/pflag" + dacli "github.com/vitwit/avail-da-module/chainclient" "github.com/vitwit/avail-da-module/types" ) +func (k Keeper) SubmitBlobTx2(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { + cdc := k.cdc + homepath := "/home/vitwit/.availsdk/keyring-test" + + cc, err := dacli.CreateChainClient(sdk.KeyringServiceName(), ctx.ChainID(), homepath, cdc.(codec.Codec)) + if err != nil { + return err + } + + msg.ValidatorAddress = cc.Address + err = cc.BroadcastTx(msg, cc.Key, sdk.AccAddress(cc.Address)) + if err != nil { + fmt.Println("error while broadcastig the txxx.........", err) + return err + } + + return nil +} + func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { // address := k.proposerAddress cdc := k.cdc @@ -39,18 +59,16 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er // create new client context clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc) - flags := *pflag.NewFlagSet("my-flags", pflag.ContinueOnError) - fmt.Println("new flagssssss.......", flags) - - msg.ValidatorAddress = "cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv" + // flags := *pflag.NewFlagSet("my-flags", pflag.ContinueOnError) // txf, err := clitx.NewFactoryCLI(clientCtx, &flags) - // fmt.Println("here the eroor with txf....", txf, err) + // // fmt.Println("here the eroor with txf....", txf, err) // if err != nil { // return err // } factory := NewFactory(clientCtx) + clientCtx.AccountRetriever = authtypes.AccountRetriever{} err = clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg) if err != nil { From df60671f282ec59c8c7bd030e8dbb919beb4f3c2 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Tue, 27 Aug 2024 21:54:25 +0530 Subject: [PATCH 16/58] fix keyring issue --- keeper/client.go | 65 ++++++++++++++++++++++++++++++++++++++++-- keeper/submitBlobTx.go | 34 +++++++++++++++++++++- 2 files changed, 96 insertions(+), 3 deletions(-) diff --git a/keeper/client.go b/keeper/client.go index aa75f94..8f0fe02 100644 --- a/keeper/client.go +++ b/keeper/client.go @@ -8,13 +8,17 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/std" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/go-bip39" + // "github.com/tendermint/starport/starport/pkg/xfilepath" + "github.com/cosmos/cosmos-sdk/client/flags" ) // var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) @@ -58,7 +62,8 @@ func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc code } // fmt.Println("from addresss.........", fromAddress) // Assuming you have access to the keyring and broadcast mode - broadcastMode := "block" + // broadcastMode := "block" + broadcastMode := flags.BroadcastSync homepath := "/home/vitwit/.availsdk/keyring-test" @@ -72,7 +77,8 @@ func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc code WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). WithKeyring(kr). WithAccountRetriever(authtypes.AccountRetriever{}). - WithClient(c).WithInterfaceRegistry(encodingConfig.InterfaceRegistry) + WithClient(c).WithInterfaceRegistry(encodingConfig.InterfaceRegistry). + WithSkipConfirmation(true) } // NewFactory creates a new Factory. @@ -117,3 +123,58 @@ type EncodingConfig struct { TxConfig client.TxConfig Amino *codec.LegacyAmino } + +// ImportMnemonic is to import existing account mnemonic in keyring +func ImportMnemonic(keyName, mnemonic, hdPath string, c client.Context) (err error) { + err = AccountCreate(keyName, mnemonic, hdPath, c) // return account also + // fmt.Println("here the accc details.......", keyName, mnemonic, hdPath) + if err != nil { + return err + } + + return nil +} + +// AccountCreate creates an account by name and mnemonic (optional) in the keyring. +func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) error { + if mnemonic == "" { + entropySeed, err := bip39.NewEntropy(256) + if err != nil { + return err + } + mnemonic, err = bip39.NewMnemonic(entropySeed) + // fmt.Println("mnemoniccccc here.....", mnemonic) + if err != nil { + return err + } + } + + algos, _ := c.Keyring.SupportedAlgorithms() + algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algos) + if err != nil { + return err + } + + path := hd.CreateHDPath(118, 0, 0).String() + // fmt.Println("pathhh......", path) + + // record, str, err := c.Keyring.NewMnemonic("test_key1", keyring.English, path, keyring.DefaultBIP39Passphrase, hd.Secp256k1) + // fmt.Println("recorddddd.......", err, str, record) + + // k, _, err = kb.NewMnemonic("test", English, types.FullFundraiserPath, DefaultBIP39Passphrase, hd.Secp256k1) + info, err := c.Keyring.NewAccount(accountName, mnemonic, keyring.DefaultBIP39Passphrase, path, algo) + // fmt.Println("after creationnnn.........", info, err) + if err != nil { + return err + } + // pk, err := info.GetPubKey() + // if err != nil { + // return err + // } + // addr := sdk.AccAddress(pk.Address()) + // fmt.Println("address hereee...", addr) + // account := c.ToAccount(info) + // account.Mnemonic = mnemonic + return c.PrintProto(info) + // return nil +} diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go index 8856830..91e38b2 100644 --- a/keeper/submitBlobTx.go +++ b/keeper/submitBlobTx.go @@ -41,18 +41,34 @@ func (k Keeper) SubmitBlobTx2(ctx sdk.Context, msg types.MsgSubmitBlobRequest) e func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { // address := k.proposerAddress cdc := k.cdc + + // var wg sy/nc.WaitGroup + + // count := 1 + + // go func() { + // for { + // if count == 0 { + // break + // } + // time.Sleep(7 * time.Second) + // fmt.Println("still in...................", ctx.BlockHeight()) + // } + // }() homepath := "/home/vitwit/.availsdk/keyring-test" // keyring kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, homepath, os.Stdin, cdc.(codec.Codec)) if err != nil { + // count = 0 fmt.Println("error while creating keyring..", err) return err } rpcClient, err := cometrpc.NewWithTimeout("http://localhost:26657", "/websocket", uint(3)) if err != nil { + // count = 0 return err } @@ -67,15 +83,31 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er // return err // } + // import mnemonic + key := "testkey" + info := ImportMnemonic(key, "", homepath, clientCtx) + fmt.Println("in submit acc infooo........", info) + + msg.ValidatorAddress = "cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv" + factory := NewFactory(clientCtx) - clientCtx.AccountRetriever = authtypes.AccountRetriever{} + // clientCtx.AccountRetriever = authtypes.AccountRetriever{} + + // get account details + + // time.Sleep(60 * time.Second) + clientCtx.FromName = key err = clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg) + // fmt.Println("errrrrrrrrrrrr............", err) if err != nil { + // count = 0 fmt.Println("error insideeeeeeeeeeee............", err) return err } + fmt.Println("after submittinggg tx") + // count = 0 return nil } From 7c02caf5c4de6f0d6369efb244c4cfd0ccdd2798 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Wed, 28 Aug 2024 12:13:32 +0530 Subject: [PATCH 17/58] import key --- keeper/abci.go | 4 +++ keeper/client.go | 64 +++++++++++++++--------------------------- keeper/submitBlobTx.go | 54 ++++++++++++----------------------- 3 files changed, 45 insertions(+), 77 deletions(-) diff --git a/keeper/abci.go b/keeper/abci.go index b986ad6..59227b6 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -65,6 +65,10 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err go func() { err := k.SubmitBlobTx(ctx, submitBlobRequest) fmt.Println("submit blob tx error.............", err) + if err == nil { + // send the blobs tx data to avail DA + + } }() return nil diff --git a/keeper/client.go b/keeper/client.go index 8f0fe02..720343b 100644 --- a/keeper/client.go +++ b/keeper/client.go @@ -1,8 +1,6 @@ package keeper import ( - "os" - cometrpc "github.com/cometbft/cometbft/rpc/client/http" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" @@ -11,7 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/std" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -21,27 +18,12 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" ) -// var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) - -func InitClientCtx(cdc *codec.ProtoCodec) client.Context { - // interfaceRegistry := codectypes.NewInterfaceRegistry() - - // // Register the custom type InjectedData - // availblobTypes.RegisterInterfaces(interfaceRegistry) - - // cdc := codec.NewProtoCodec(interfaceRegistry) - // cdc := codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) - - clientCtx := client.Context{}. - WithCodec(cdc). - WithTxConfig(authTx.NewTxConfig(cdc, authTx.DefaultSignModes)). - WithChainID("demo"). - WithKeyringDir("~/.availsdk/keyring-test"). - WithHomeDir("~/.availsdk"). - WithInput(os.Stdin) +const ( + defaultGasAdjustment = 1.0 + defaultGasLimit = 300000 +) - return clientCtx -} +// var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc codec.BinaryCodec) client.Context { encodingConfig := MakeEncodingConfig() @@ -55,11 +37,11 @@ func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc code // fmt.Println("address heree......", address) // sdk.AccAddressFromBech32() - fromAddress, err := sdk.AccAddressFromBech32("cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv") + // fromAddress, err := sdk.AccAddressFromBech32(kr.FromAddress) // fmt.Println("here errorr...", err) - if err != nil { - // return err - } + // if err != nil { + // // return err + // } // fmt.Println("from addresss.........", fromAddress) // Assuming you have access to the keyring and broadcast mode // broadcastMode := "block" @@ -70,8 +52,8 @@ func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc code return client.Context{}. WithCodec(cdc.(codec.Codec)). WithChainID(chainID). - WithFromAddress(fromAddress). - WithFromName("alice"). + // WithFromAddress(kr.fromAddress). + WithFromName("testkey"). WithKeyringDir(homepath). WithBroadcastMode(broadcastMode). WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). @@ -86,8 +68,8 @@ func NewFactory(clientCtx client.Context) tx.Factory { return tx.Factory{}. WithChainID(clientCtx.ChainID). WithKeybase(clientCtx.Keyring). - // WithGas(defaultGasLimit). - // WithGasAdjustment(defaultGasAdjustment). + WithGas(defaultGasLimit). + WithGasAdjustment(defaultGasAdjustment). WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). WithAccountRetriever(clientCtx.AccountRetriever). WithTxConfig(clientCtx.TxConfig) @@ -125,34 +107,34 @@ type EncodingConfig struct { } // ImportMnemonic is to import existing account mnemonic in keyring -func ImportMnemonic(keyName, mnemonic, hdPath string, c client.Context) (err error) { - err = AccountCreate(keyName, mnemonic, hdPath, c) // return account also +func ImportMnemonic(keyName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { + info, err := AccountCreate(keyName, mnemonic, hdPath, c) // return account also // fmt.Println("here the accc details.......", keyName, mnemonic, hdPath) if err != nil { - return err + return nil, err } - return nil + return info, nil } // AccountCreate creates an account by name and mnemonic (optional) in the keyring. -func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) error { +func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { if mnemonic == "" { entropySeed, err := bip39.NewEntropy(256) if err != nil { - return err + return nil, err } mnemonic, err = bip39.NewMnemonic(entropySeed) // fmt.Println("mnemoniccccc here.....", mnemonic) if err != nil { - return err + return nil, err } } algos, _ := c.Keyring.SupportedAlgorithms() algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algos) if err != nil { - return err + return nil, err } path := hd.CreateHDPath(118, 0, 0).String() @@ -165,7 +147,7 @@ func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) error info, err := c.Keyring.NewAccount(accountName, mnemonic, keyring.DefaultBIP39Passphrase, path, algo) // fmt.Println("after creationnnn.........", info, err) if err != nil { - return err + return nil, err } // pk, err := info.GetPubKey() // if err != nil { @@ -175,6 +157,6 @@ func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) error // fmt.Println("address hereee...", addr) // account := c.ToAccount(info) // account.Mnemonic = mnemonic - return c.PrintProto(info) + return info, nil // return nil } diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go index 91e38b2..3905320 100644 --- a/keeper/submitBlobTx.go +++ b/keeper/submitBlobTx.go @@ -2,6 +2,7 @@ package keeper import ( "fmt" + "log" "os" cometrpc "github.com/cometbft/cometbft/rpc/client/http" @@ -42,72 +43,53 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er // address := k.proposerAddress cdc := k.cdc - // var wg sy/nc.WaitGroup - - // count := 1 - - // go func() { - // for { - // if count == 0 { - // break - // } - // time.Sleep(7 * time.Second) - // fmt.Println("still in...................", ctx.BlockHeight()) - // } - // }() homepath := "/home/vitwit/.availsdk/keyring-test" // keyring kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, homepath, os.Stdin, cdc.(codec.Codec)) if err != nil { - // count = 0 fmt.Println("error while creating keyring..", err) return err } rpcClient, err := cometrpc.NewWithTimeout("http://localhost:26657", "/websocket", uint(3)) if err != nil { - // count = 0 return err } // create new client context clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc) - // flags := *pflag.NewFlagSet("my-flags", pflag.ContinueOnError) - - // txf, err := clitx.NewFactoryCLI(clientCtx, &flags) - // // fmt.Println("here the eroor with txf....", txf, err) - // if err != nil { - // return err - // } - // import mnemonic key := "testkey" - info := ImportMnemonic(key, "", homepath, clientCtx) - fmt.Println("in submit acc infooo........", info) + info, err := ImportMnemonic(key, "", homepath, clientCtx) + fmt.Println("infoo heree........", info) + // _ = info + // fmt.Println("in submit acc infooo........", info) + pk, err := info.GetPubKey() + if err != nil { + return err + } + addr := sdk.AccAddress(pk.Address()) + fmt.Println("addresss........", addr) - msg.ValidatorAddress = "cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv" + // add, err := sdk.AccAddressFromBech32(pk.Address().String()) + log.Println("aaa.......", addr.String()) + // log.Fatal("proto valuee", clientCtx.PrintProto(info)) - factory := NewFactory(clientCtx) - // clientCtx.AccountRetriever = authtypes.AccountRetriever{} + msg.ValidatorAddress = addr.String() - // get account details + factory := NewFactory(clientCtx) - // time.Sleep(60 * time.Second) - clientCtx.FromName = key + clientCtx.FromName = "key" + clientCtx.FromAddress = addr err = clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg) - // fmt.Println("errrrrrrrrrrrr............", err) if err != nil { - // count = 0 - fmt.Println("error insideeeeeeeeeeee............", err) return err } - fmt.Println("after submittinggg tx") - // count = 0 return nil } From ddd2e37b553bcfe12c45a2b8360ead4eaae6677d Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Wed, 28 Aug 2024 23:39:29 +0530 Subject: [PATCH 18/58] fix --- chainclient/create_client.go | 8 ++--- keeper/client.go | 60 ++++++++++++++++++++++++++++-------- keeper/submitBlobTx.go | 35 ++++++++++----------- 3 files changed, 68 insertions(+), 35 deletions(-) diff --git a/chainclient/create_client.go b/chainclient/create_client.go index e35f873..61375e7 100644 --- a/chainclient/create_client.go +++ b/chainclient/create_client.go @@ -77,10 +77,10 @@ func GetClient(chainID string, cc ChainClient, homePath string, codec codec.Code // fmt.Println("mnemonic and chain id....", c.Mnemonic, c.ChainName, c.Key) - // err = c.ImportMnemonic(c.Key, c.Mnemonic, c.HDPath) - // if err != nil { - // return nil, err - // } + err = c.ImportMnemonic(c.Key, c.Mnemonic, c.HDPath) + if err != nil { + return nil, err + } return c, nil } diff --git a/keeper/client.go b/keeper/client.go index 720343b..dfba1fe 100644 --- a/keeper/client.go +++ b/keeper/client.go @@ -1,21 +1,26 @@ package keeper import ( + "fmt" + cometrpc "github.com/cometbft/cometbft/rpc/client/http" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/std" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/go-bip39" // "github.com/tendermint/starport/starport/pkg/xfilepath" - "github.com/cosmos/cosmos-sdk/client/flags" + + "github.com/cosmos/cosmos-sdk/types/module" ) const ( @@ -37,11 +42,11 @@ func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc code // fmt.Println("address heree......", address) // sdk.AccAddressFromBech32() - // fromAddress, err := sdk.AccAddressFromBech32(kr.FromAddress) - // fmt.Println("here errorr...", err) - // if err != nil { - // // return err - // } + fromAddress, err := sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") + fmt.Println("here errorr...", err) + if err != nil { + // return err + } // fmt.Println("from addresss.........", fromAddress) // Assuming you have access to the keyring and broadcast mode // broadcastMode := "block" @@ -52,7 +57,7 @@ func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc code return client.Context{}. WithCodec(cdc.(codec.Codec)). WithChainID(chainID). - // WithFromAddress(kr.fromAddress). + WithFromAddress(fromAddress). WithFromName("testkey"). WithKeyringDir(homepath). WithBroadcastMode(broadcastMode). @@ -76,7 +81,7 @@ func NewFactory(clientCtx client.Context) tx.Factory { } // MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. -func MakeEncodingConfig() EncodingConfig { +func MakeEncodingConfig(modules ...module.AppModuleBasic) EncodingConfig { aminoCodec := codec.NewLegacyAmino() interfaceRegistry := codectypes.NewInterfaceRegistry() codec := codec.NewProtoCodec(interfaceRegistry) @@ -89,14 +94,38 @@ func MakeEncodingConfig() EncodingConfig { Amino: aminoCodec, } + mb := module.NewBasicManager(modules...) + std.RegisterLegacyAminoCodec(encCfg.Amino) std.RegisterInterfaces(encCfg.InterfaceRegistry) - // mb.RegisterLegacyAminoCodec(encCfg.Amino) - // mb.RegisterInterfaces(encCfg.InterfaceRegistry) + mb.RegisterLegacyAminoCodec(encCfg.Amino) + mb.RegisterInterfaces(encCfg.InterfaceRegistry) return encCfg } +// func MakeTestEncodingConfig(modules ...module.AppModuleBasic) TestEncodingConfig { +// aminoCodec := codec.NewLegacyAmino() +// interfaceRegistry := testutil.CodecOptions{}.NewInterfaceRegistry() +// codec := codec.NewProtoCodec(interfaceRegistry) + +// encCfg := TestEncodingConfig{ +// InterfaceRegistry: interfaceRegistry, +// Codec: codec, +// TxConfig: tx.NewTxConfig(codec, tx.DefaultSignModes), +// Amino: aminoCodec, +// } + +// mb := module.NewBasicManager(modules...) + +// std.RegisterLegacyAminoCodec(encCfg.Amino) +// std.RegisterInterfaces(encCfg.InterfaceRegistry) +// mb.RegisterLegacyAminoCodec(encCfg.Amino) +// mb.RegisterInterfaces(encCfg.InterfaceRegistry) + +// return encCfg +// } + // EncodingConfig specifies the concrete encoding types to use for a given app. // This is provided for compatibility between protobuf and amino implementations. type EncodingConfig struct { @@ -125,7 +154,7 @@ func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) (*key return nil, err } mnemonic, err = bip39.NewMnemonic(entropySeed) - // fmt.Println("mnemoniccccc here.....", mnemonic) + fmt.Println("mnemoniccccc here.....", mnemonic) if err != nil { return nil, err } @@ -145,16 +174,21 @@ func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) (*key // k, _, err = kb.NewMnemonic("test", English, types.FullFundraiserPath, DefaultBIP39Passphrase, hd.Secp256k1) info, err := c.Keyring.NewAccount(accountName, mnemonic, keyring.DefaultBIP39Passphrase, path, algo) - // fmt.Println("after creationnnn.........", info, err) + fmt.Println("after creationnnn.........", info, err) if err != nil { return nil, err } // pk, err := info.GetPubKey() // if err != nil { - // return err + // return nil, err // } + // addr := sdk.AccAddress(pk.Address()) // fmt.Println("address hereee...", addr) + + // aa, err := info.GetAddress() + // fmt.Println("here aa and err.......", aa, err) + // account := c.ToAccount(info) // account.Mnemonic = mnemonic return info, nil diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go index 3905320..2a81cf2 100644 --- a/keeper/submitBlobTx.go +++ b/keeper/submitBlobTx.go @@ -2,7 +2,6 @@ package keeper import ( "fmt" - "log" "os" cometrpc "github.com/cometbft/cometbft/rpc/client/http" @@ -61,29 +60,29 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er // create new client context clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc) - // import mnemonic + // // import mnemonic key := "testkey" - info, err := ImportMnemonic(key, "", homepath, clientCtx) - fmt.Println("infoo heree........", info) - // _ = info - // fmt.Println("in submit acc infooo........", info) - pk, err := info.GetPubKey() - if err != nil { - return err - } - addr := sdk.AccAddress(pk.Address()) - fmt.Println("addresss........", addr) + // mnemonic := "kingdom blade tunnel gate decrease glass crater crash provide word crystal grape that hold dust retreat speak exit blind car enroll patient face wasp" + // info, err := ImportMnemonic(key, mnemonic, homepath, clientCtx) + // fmt.Println("infoo heree........", info) + + // pk, err := info.GetPubKey() + // if err != nil { + // return err + // } + + // addr := sdk.AccAddress(pk.Address()) + // fmt.Println("address hereee...", addr) - // add, err := sdk.AccAddressFromBech32(pk.Address().String()) - log.Println("aaa.......", addr.String()) - // log.Fatal("proto valuee", clientCtx.PrintProto(info)) + valAddr, err := sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") + fmt.Println("val addrr and error...", valAddr, err) - msg.ValidatorAddress = addr.String() + clientCtx.FromName = key + clientCtx.FromAddress = valAddr factory := NewFactory(clientCtx) - clientCtx.FromName = "key" - clientCtx.FromAddress = addr + msg.ValidatorAddress = valAddr.String() err = clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg) if err != nil { From 8433f8bd54a70f87274eedb3a0b6141d37320fa8 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Wed, 28 Aug 2024 23:41:13 +0530 Subject: [PATCH 19/58] refactor --- keeper/submitBlobTx.go | 54 +++++++++++++++++------------------------- 1 file changed, 22 insertions(+), 32 deletions(-) diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go index 2a81cf2..eb5a8af 100644 --- a/keeper/submitBlobTx.go +++ b/keeper/submitBlobTx.go @@ -39,54 +39,44 @@ func (k Keeper) SubmitBlobTx2(ctx sdk.Context, msg types.MsgSubmitBlobRequest) e } func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { - // address := k.proposerAddress - cdc := k.cdc + // Define keyring and RPC client configuration - homepath := "/home/vitwit/.availsdk/keyring-test" - // keyring - kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, - homepath, os.Stdin, cdc.(codec.Codec)) + homePath := "/home/vitwit/.availsdk/keyring-test" + keyName := "testkey" + rpcAddress := "http://localhost:26657" + // Create a keyring + kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, homePath, os.Stdin, k.cdc.(codec.Codec)) if err != nil { - fmt.Println("error while creating keyring..", err) - return err + return fmt.Errorf("error creating keyring: %w", err) } - rpcClient, err := cometrpc.NewWithTimeout("http://localhost:26657", "/websocket", uint(3)) + // Create an RPC client + rpcClient, err := cometrpc.NewWithTimeout(rpcAddress, "/websocket", 3) if err != nil { - return err + return fmt.Errorf("error creating RPC client: %w", err) } - // create new client context - clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc) - - // // import mnemonic - key := "testkey" - // mnemonic := "kingdom blade tunnel gate decrease glass crater crash provide word crystal grape that hold dust retreat speak exit blind car enroll patient face wasp" - // info, err := ImportMnemonic(key, mnemonic, homepath, clientCtx) - // fmt.Println("infoo heree........", info) - - // pk, err := info.GetPubKey() - // if err != nil { - // return err - // } - - // addr := sdk.AccAddress(pk.Address()) - // fmt.Println("address hereee...", addr) + // Create a new client context + clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), k.cdc) + // Retrieve the validator address (replace with actual logic to get the address) valAddr, err := sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") - fmt.Println("val addrr and error...", valAddr, err) + if err != nil { + return fmt.Errorf("error parsing validator address: %w", err) + } - clientCtx.FromName = key + // Set the client context's from fields + clientCtx.FromName = keyName clientCtx.FromAddress = valAddr + // Create a transaction factory and set the validator address in the message factory := NewFactory(clientCtx) - msg.ValidatorAddress = valAddr.String() - err = clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg) - if err != nil { - return err + // Generate and broadcast the transaction + if err := clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg); err != nil { + return fmt.Errorf("error broadcasting transaction: %w", err) } return nil From 1758c2788fd910538ab96c09001521430b5a5a70 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Thu, 29 Aug 2024 00:59:08 +0530 Subject: [PATCH 20/58] update submitblob tx --- keeper/client.go | 24 ++----- keeper/submitBlobTx.go | 150 +++++++++++++---------------------------- 2 files changed, 50 insertions(+), 124 deletions(-) diff --git a/keeper/client.go b/keeper/client.go index dfba1fe..27796d6 100644 --- a/keeper/client.go +++ b/keeper/client.go @@ -30,29 +30,13 @@ const ( // var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) -func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc codec.BinaryCodec) client.Context { +func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, + cdc codec.BinaryCodec, homepath string, fromAddress sdk.AccAddress) client.Context { encodingConfig := MakeEncodingConfig() - // authtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) - // cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) - // sdk.RegisterInterfaces(encodingConfig.InterfaceRegistry) - // staking.RegisterInterfaces(encodingConfig.InterfaceRegistry) - // cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) - - // chainID := ctx.ChainID() - - // fmt.Println("address heree......", address) - // sdk.AccAddressFromBech32() - fromAddress, err := sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") - fmt.Println("here errorr...", err) - if err != nil { - // return err - } - // fmt.Println("from addresss.........", fromAddress) - // Assuming you have access to the keyring and broadcast mode - // broadcastMode := "block" + broadcastMode := flags.BroadcastSync - homepath := "/home/vitwit/.availsdk/keyring-test" + // homepath := "/home/vitwit/.availsdk" return client.Context{}. WithCodec(cdc.(codec.Codec)). diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go index eb5a8af..b096351 100644 --- a/keeper/submitBlobTx.go +++ b/keeper/submitBlobTx.go @@ -5,16 +5,13 @@ import ( "os" cometrpc "github.com/cometbft/cometbft/rpc/client/http" - "github.com/cosmos/cosmos-sdk/client" clitx "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" - authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/spf13/pflag" dacli "github.com/vitwit/avail-da-module/chainclient" "github.com/vitwit/avail-da-module/types" ) @@ -41,8 +38,8 @@ func (k Keeper) SubmitBlobTx2(ctx sdk.Context, msg types.MsgSubmitBlobRequest) e func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { // Define keyring and RPC client configuration - homePath := "/home/vitwit/.availsdk/keyring-test" - keyName := "testkey" + homePath := "/home/vitwit/.availsdk" + keyName := "alice" rpcAddress := "http://localhost:26657" // Create a keyring @@ -51,6 +48,29 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er return fmt.Errorf("error creating keyring: %w", err) } + // List all keys in the keyring + // keys, err := kr.List() + // if err != nil { + // fmt.Println("error listing keys:", err) + // } + + info, err := kr.Key(keyName) + // log.Println("uuu....", info, err) + + valAddr, err := info.GetAddress() + + // valAddr, err := sdk.AccAddressFromBech32(addr.String()) + // fmt.Println("val addr, err..", valAddr, err, addr) + + // fmt.Println("keysss........", keys) + + // // Print out the keys + // for _, keyInfo := range keys { + // addr, err := keyInfo.GetAddress() + // fmt.Println("err..", err) + // fmt.Printf("Name: %s, Address: %s\n", keyInfo.Name, addr) + // } + // Create an RPC client rpcClient, err := cometrpc.NewWithTimeout(rpcAddress, "/websocket", 3) if err != nil { @@ -58,21 +78,36 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er } // Create a new client context - clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), k.cdc) + clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), k.cdc, homePath, valAddr) // Retrieve the validator address (replace with actual logic to get the address) - valAddr, err := sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") - if err != nil { - return fmt.Errorf("error parsing validator address: %w", err) - } + // valAddr, err = sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") + // if err != nil { + // return fmt.Errorf("error parsing validator address: %w", err) + // } // Set the client context's from fields clientCtx.FromName = keyName clientCtx.FromAddress = valAddr + // Fetch account number and sequence from the blockchain + accountRetriever := authtypes.AccountRetriever{} + account, err := accountRetriever.GetAccount(clientCtx, valAddr) + if err != nil { + return fmt.Errorf("error retrieving account: %w", err) + } + + fmt.Println("account details......", account.GetAccountNumber(), account.GetSequence()) + + // Set the correct account number and sequence + factory := NewFactory(clientCtx). + WithAccountNumber(account.GetAccountNumber()). + WithSequence(account.GetSequence()) + // Create a transaction factory and set the validator address in the message - factory := NewFactory(clientCtx) + // factory := NewFactory(clientCtx) msg.ValidatorAddress = valAddr.String() + // time.Sleep(10 * time.Second) // Generate and broadcast the transaction if err := clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg); err != nil { @@ -81,96 +116,3 @@ func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) er return nil } - -func (k Keeper) SubmitBlobTx1(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { - cdc := k.cdc - chainID := ctx.ChainID() - address := k.proposerAddress - - fmt.Println("address heree......", address) - // fromAddress := sdk.AccAddress(address) - // Assuming you have access to the keyring and broadcast mode - broadcastMode := "block" - - homepath := "/home/vitwit/.availsdk/keyring-test" - - // keyring - kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, - homepath, os.Stdin, cdc.(codec.Codec)) - - if err != nil { - fmt.Println("error while creating keyring..", err) - return err - } - - rpcClient, err := cometrpc.NewWithTimeout("http://localhost:26657", "/websocket", uint(3)) - if err != nil { - return err - } - - addr, err := sdk.AccAddressFromBech32("cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv") - fmt.Println("address and errorr......", addr, err) - - // clientCtx := NewClientCtx(kr, rpcClient) - - // clientCtx := client.Context{}. - // WithCodec(cdc). - // WithTxConfig(authTx.NewTxConfig(cdc, authTx.DefaultSignModes)). - // WithChainID("demo"). - // WithKeyringDir("~/.availsdk/keyring-test"). - // WithHomeDir("~/.availsdk"). - // WithInput(os.Stdin) - - // k.keyring.Backend() - - clientCtx := client.Context{}. - WithCodec(cdc.(codec.Codec)). - WithChainID(chainID). - WithFromAddress(addr). - WithFromName("alice"). - // WithKeyringDir("~/.availsdk/keyring-test"). - WithKeyringDir(homepath). - WithBroadcastMode(broadcastMode). - WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). - WithKeyring(kr). - WithAccountRetriever(authtypes.AccountRetriever{}). - WithClient(rpcClient). - WithSkipConfirmation(true) - - // a, b, c := clientCtx.AccountRetriever.GetAccountNumberSequence(clientCtx, addr) - // fmt.Println("coming upto hereeeee.........", a, b, c) - msg.ValidatorAddress = "cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv" - - fmt.Println("validator addressssssss............, ", msg.ValidatorAddress) - - flags := *pflag.NewFlagSet("my-flags", pflag.ContinueOnError) - fmt.Println("new flagssssss.......", flags) - // fmt.Println("account and sequence numberrr.......", flags.) - // Set any additional flags here, like fees, gas, etc. - - fmt.Println("txxxxxxxxxxx........", clientCtx.ChainID) - fmt.Println("txxxxxxxxxxx........", clientCtx.CmdContext) - fmt.Println("txxxxxxxxxxx........", clientCtx.Codec) - fmt.Println("txxxxxxxxxxx........", clientCtx.FromAddress.String()) - fmt.Println("txxxxxxxxxxx........", clientCtx.BroadcastMode) - fmt.Println("aaaaaaaa.......", clientCtx.TxConfig) - fmt.Println("aaaaaaaa.......", clientCtx.AccountRetriever) - - // err = clitx.GenerateOrBroadcastTxCLI(clientCtx, &flags, &msg) - txf, err := clitx.NewFactoryCLI(clientCtx, &flags) - fmt.Println("here the eroor with txf....", txf, err) - if err != nil { - return err - } - - err = clitx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, &msg) - if err != nil { - fmt.Println("error insideeeeeeeeeeee............", err) - return err - } - - fmt.Println("heree.....") - - // handle the response, log, or return as needed - return nil -} From 23c3af7470f42d2c9c6a6ebefcbf142f20891517 Mon Sep 17 00:00:00 2001 From: saiteja Date: Thu, 29 Aug 2024 10:41:55 +0530 Subject: [PATCH 21/58] new query --- go.mod | 4 +- keeper/keeper.go | 5 + keeper/query_server.go | 8 + proto/sdk/avail/v1beta1/query.proto | 24 ++ types/query.pb.go | 530 ++++++++++++++++++++++++---- types/query.pb.gw.go | 83 +++++ 6 files changed, 589 insertions(+), 65 deletions(-) diff --git a/go.mod b/go.mod index 658077f..0f1fc6f 100644 --- a/go.mod +++ b/go.mod @@ -63,7 +63,7 @@ require ( github.com/cometbft/cometbft-db v0.9.1 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/cosmos-db v1.0.2 // indirect - github.com/cosmos/go-bip39 v1.0.0 // indirect + github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v1.1.2 // indirect github.com/cosmos/ics23/go v0.10.0 // indirect @@ -153,7 +153,7 @@ require ( github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.11.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect + github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.19.0 // indirect github.com/stretchr/testify v1.9.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect diff --git a/keeper/keeper.go b/keeper/keeper.go index e32c902..38d3fdb 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -110,3 +110,8 @@ func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatu err := updateBlobStatus(ctx, store, *req.BlocksRange, status) return &types.MsgUpdateBlobStatusResponse{}, err } + +func (k *Keeper) SubmitBlobStatus(ctx sdk.Context, _ *types.QuerySubmitBlobStatusRequest) (*types.QuerySubmitBlobStatusResponse, error) { + // Todo: implement query + return nil, nil +} diff --git a/keeper/query_server.go b/keeper/query_server.go index 0ad3405..bf70f7c 100644 --- a/keeper/query_server.go +++ b/keeper/query_server.go @@ -5,6 +5,7 @@ import ( "time" "cosmossdk.io/collections" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/vitwit/avail-da-module/types" ) @@ -89,3 +90,10 @@ func (qs queryServer) ExpiredBlocks(ctx context.Context, _ *types.QueryExpiredBl ExpiredBlocks: expiredBlocks, }, nil } + +func (qs queryServer) SubmitBlobStatus(ctx context.Context, req *types.QuerySubmitBlobStatusRequest) (*types.QuerySubmitBlobStatusResponse, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + + //TODO: query the light client + return qs.k.SubmitBlobStatus(sdkCtx, req) +} diff --git a/proto/sdk/avail/v1beta1/query.proto b/proto/sdk/avail/v1beta1/query.proto index 8c7998a..f5f850a 100644 --- a/proto/sdk/avail/v1beta1/query.proto +++ b/proto/sdk/avail/v1beta1/query.proto @@ -5,29 +5,52 @@ import "gogoproto/gogo.proto"; import "google/api/annotations.proto"; import "sdk/avail/v1beta1/validator.proto"; import "google/protobuf/timestamp.proto"; +import "sdk/avail/v1beta1/tx.proto"; option go_package = "github.com/vitwit/avail-da-module/types"; +// query request +message QuerySubmitBlobStatusRequest { + Range range = 1; +} + +// query response +message QuerySubmitBlobStatusResponse { + string status = 1; +} + // Query defines the gRPC querier service. service Query { + + // submit Blob Status + rpc SubmitBlobStatus(QuerySubmitBlobStatusRequest) + returns (QuerySubmitBlobStatusResponse) { + option (google.api.http).get = "/availblob/v1beta1/submitBlobStatus"; + } // Validators returns registered validators of the module. rpc Validators(QueryValidatorsRequest) returns (QueryValidatorsResponse) { option (google.api.http).get = "/availblob/v1beta1/validators"; } + + + // Todo: will be removed rpc AvailAddress(QueryAvailAddressRequest) returns (QueryAvailAddressResponse) { option (google.api.http).get = "/availblob/v1beta1/avail_address"; } + // proven height rpc ProvenHeight(QueryProvenHeightRequest) returns (QueryProvenHeightResponse) { option (google.api.http).get = "/availblob/v1beta1/proven_height"; } + // pending blocks rpc PendingBlocks(QueryPendingBlocksRequest) returns (QueryPendingBlocksResponse) { option (google.api.http).get = "/availblob/v1beta1/pending_blocks"; } + // expired blocks rpc ExpiredBlocks(QueryExpiredBlocksRequest) returns (QueryExpiredBlocksResponse) { option (google.api.http).get = "/availblob/v1beta1/expired_blocks"; } @@ -52,6 +75,7 @@ message QueryAvailAddressResponse { string avail_address = 1; } +// proven Height message QueryProvenHeightRequest {} message QueryProvenHeightResponse { diff --git a/types/query.pb.go b/types/query.pb.go index 44f985a..a66c02c 100644 --- a/types/query.pb.go +++ b/types/query.pb.go @@ -33,6 +33,96 @@ var _ = time.Kitchen // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +// query request +type QuerySubmitBlobStatusRequest struct { + Range *Range `protobuf:"bytes,1,opt,name=range,proto3" json:"range,omitempty"` +} + +func (m *QuerySubmitBlobStatusRequest) Reset() { *m = QuerySubmitBlobStatusRequest{} } +func (m *QuerySubmitBlobStatusRequest) String() string { return proto.CompactTextString(m) } +func (*QuerySubmitBlobStatusRequest) ProtoMessage() {} +func (*QuerySubmitBlobStatusRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_30ff5d91ce731c68, []int{0} +} +func (m *QuerySubmitBlobStatusRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QuerySubmitBlobStatusRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QuerySubmitBlobStatusRequest.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 *QuerySubmitBlobStatusRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QuerySubmitBlobStatusRequest.Merge(m, src) +} +func (m *QuerySubmitBlobStatusRequest) XXX_Size() int { + return m.Size() +} +func (m *QuerySubmitBlobStatusRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QuerySubmitBlobStatusRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QuerySubmitBlobStatusRequest proto.InternalMessageInfo + +func (m *QuerySubmitBlobStatusRequest) GetRange() *Range { + if m != nil { + return m.Range + } + return nil +} + +// query response +type QuerySubmitBlobStatusResponse struct { + Status string `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"` +} + +func (m *QuerySubmitBlobStatusResponse) Reset() { *m = QuerySubmitBlobStatusResponse{} } +func (m *QuerySubmitBlobStatusResponse) String() string { return proto.CompactTextString(m) } +func (*QuerySubmitBlobStatusResponse) ProtoMessage() {} +func (*QuerySubmitBlobStatusResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_30ff5d91ce731c68, []int{1} +} +func (m *QuerySubmitBlobStatusResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QuerySubmitBlobStatusResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QuerySubmitBlobStatusResponse.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 *QuerySubmitBlobStatusResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QuerySubmitBlobStatusResponse.Merge(m, src) +} +func (m *QuerySubmitBlobStatusResponse) XXX_Size() int { + return m.Size() +} +func (m *QuerySubmitBlobStatusResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QuerySubmitBlobStatusResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QuerySubmitBlobStatusResponse proto.InternalMessageInfo + +func (m *QuerySubmitBlobStatusResponse) GetStatus() string { + if m != nil { + return m.Status + } + return "" +} + // QueryValidatorsRequest is the request type for the Query/Validators RPC method. type QueryValidatorsRequest struct { } @@ -41,7 +131,7 @@ func (m *QueryValidatorsRequest) Reset() { *m = QueryValidatorsRequest{} func (m *QueryValidatorsRequest) String() string { return proto.CompactTextString(m) } func (*QueryValidatorsRequest) ProtoMessage() {} func (*QueryValidatorsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_30ff5d91ce731c68, []int{0} + return fileDescriptor_30ff5d91ce731c68, []int{2} } func (m *QueryValidatorsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -80,7 +170,7 @@ func (m *QueryValidatorsResponse) Reset() { *m = QueryValidatorsResponse func (m *QueryValidatorsResponse) String() string { return proto.CompactTextString(m) } func (*QueryValidatorsResponse) ProtoMessage() {} func (*QueryValidatorsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_30ff5d91ce731c68, []int{1} + return fileDescriptor_30ff5d91ce731c68, []int{3} } func (m *QueryValidatorsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -125,7 +215,7 @@ func (m *QueryAvailAddressRequest) Reset() { *m = QueryAvailAddressReque func (m *QueryAvailAddressRequest) String() string { return proto.CompactTextString(m) } func (*QueryAvailAddressRequest) ProtoMessage() {} func (*QueryAvailAddressRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_30ff5d91ce731c68, []int{2} + return fileDescriptor_30ff5d91ce731c68, []int{4} } func (m *QueryAvailAddressRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -170,7 +260,7 @@ func (m *QueryAvailAddressResponse) Reset() { *m = QueryAvailAddressResp func (m *QueryAvailAddressResponse) String() string { return proto.CompactTextString(m) } func (*QueryAvailAddressResponse) ProtoMessage() {} func (*QueryAvailAddressResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_30ff5d91ce731c68, []int{3} + return fileDescriptor_30ff5d91ce731c68, []int{5} } func (m *QueryAvailAddressResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -206,6 +296,7 @@ func (m *QueryAvailAddressResponse) GetAvailAddress() string { return "" } +// proven Height type QueryProvenHeightRequest struct { } @@ -213,7 +304,7 @@ func (m *QueryProvenHeightRequest) Reset() { *m = QueryProvenHeightReque func (m *QueryProvenHeightRequest) String() string { return proto.CompactTextString(m) } func (*QueryProvenHeightRequest) ProtoMessage() {} func (*QueryProvenHeightRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_30ff5d91ce731c68, []int{4} + return fileDescriptor_30ff5d91ce731c68, []int{6} } func (m *QueryProvenHeightRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -250,7 +341,7 @@ func (m *QueryProvenHeightResponse) Reset() { *m = QueryProvenHeightResp func (m *QueryProvenHeightResponse) String() string { return proto.CompactTextString(m) } func (*QueryProvenHeightResponse) ProtoMessage() {} func (*QueryProvenHeightResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_30ff5d91ce731c68, []int{5} + return fileDescriptor_30ff5d91ce731c68, []int{7} } func (m *QueryProvenHeightResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -295,7 +386,7 @@ func (m *BlockWithExpiration) Reset() { *m = BlockWithExpiration{} } func (m *BlockWithExpiration) String() string { return proto.CompactTextString(m) } func (*BlockWithExpiration) ProtoMessage() {} func (*BlockWithExpiration) Descriptor() ([]byte, []int) { - return fileDescriptor_30ff5d91ce731c68, []int{6} + return fileDescriptor_30ff5d91ce731c68, []int{8} } func (m *BlockWithExpiration) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -345,7 +436,7 @@ func (m *QueryPendingBlocksRequest) Reset() { *m = QueryPendingBlocksReq func (m *QueryPendingBlocksRequest) String() string { return proto.CompactTextString(m) } func (*QueryPendingBlocksRequest) ProtoMessage() {} func (*QueryPendingBlocksRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_30ff5d91ce731c68, []int{7} + return fileDescriptor_30ff5d91ce731c68, []int{9} } func (m *QueryPendingBlocksRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -382,7 +473,7 @@ func (m *QueryPendingBlocksResponse) Reset() { *m = QueryPendingBlocksRe func (m *QueryPendingBlocksResponse) String() string { return proto.CompactTextString(m) } func (*QueryPendingBlocksResponse) ProtoMessage() {} func (*QueryPendingBlocksResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_30ff5d91ce731c68, []int{8} + return fileDescriptor_30ff5d91ce731c68, []int{10} } func (m *QueryPendingBlocksResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -425,7 +516,7 @@ func (m *QueryExpiredBlocksRequest) Reset() { *m = QueryExpiredBlocksReq func (m *QueryExpiredBlocksRequest) String() string { return proto.CompactTextString(m) } func (*QueryExpiredBlocksRequest) ProtoMessage() {} func (*QueryExpiredBlocksRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_30ff5d91ce731c68, []int{9} + return fileDescriptor_30ff5d91ce731c68, []int{11} } func (m *QueryExpiredBlocksRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -463,7 +554,7 @@ func (m *QueryExpiredBlocksResponse) Reset() { *m = QueryExpiredBlocksRe func (m *QueryExpiredBlocksResponse) String() string { return proto.CompactTextString(m) } func (*QueryExpiredBlocksResponse) ProtoMessage() {} func (*QueryExpiredBlocksResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_30ff5d91ce731c68, []int{10} + return fileDescriptor_30ff5d91ce731c68, []int{12} } func (m *QueryExpiredBlocksResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -507,6 +598,8 @@ func (m *QueryExpiredBlocksResponse) GetExpiredBlocks() []*BlockWithExpiration { } func init() { + proto.RegisterType((*QuerySubmitBlobStatusRequest)(nil), "sdk.avail.v1beta1.QuerySubmitBlobStatusRequest") + proto.RegisterType((*QuerySubmitBlobStatusResponse)(nil), "sdk.avail.v1beta1.QuerySubmitBlobStatusResponse") proto.RegisterType((*QueryValidatorsRequest)(nil), "sdk.avail.v1beta1.QueryValidatorsRequest") proto.RegisterType((*QueryValidatorsResponse)(nil), "sdk.avail.v1beta1.QueryValidatorsResponse") proto.RegisterType((*QueryAvailAddressRequest)(nil), "sdk.avail.v1beta1.QueryAvailAddressRequest") @@ -523,48 +616,54 @@ func init() { func init() { proto.RegisterFile("sdk/avail/v1beta1/query.proto", fileDescriptor_30ff5d91ce731c68) } var fileDescriptor_30ff5d91ce731c68 = []byte{ - // 653 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x93, 0x41, 0x6e, 0xd3, 0x40, - 0x14, 0x86, 0x33, 0x2d, 0xad, 0x60, 0x9a, 0x22, 0x3a, 0xa0, 0x12, 0x4c, 0x9b, 0xa4, 0xae, 0x80, - 0x94, 0x52, 0x5b, 0x2d, 0x17, 0xa0, 0x11, 0xa8, 0x6c, 0x90, 0x20, 0x42, 0x20, 0x21, 0xa1, 0x68, - 0x5c, 0x0f, 0xce, 0x28, 0x89, 0xc7, 0xf5, 0x8c, 0x03, 0xdd, 0xb2, 0x64, 0x55, 0xa9, 0x0b, 0x2e, - 0xc2, 0x21, 0xba, 0xac, 0xc4, 0x86, 0x15, 0xa0, 0x86, 0x23, 0x70, 0x00, 0xe4, 0xf1, 0xd8, 0xb5, - 0x9b, 0x71, 0x15, 0x76, 0x4d, 0xff, 0xff, 0xbd, 0xf7, 0xbd, 0x79, 0xfe, 0xe1, 0x2a, 0x77, 0xfb, - 0x36, 0x1e, 0x61, 0x3a, 0xb0, 0x47, 0xdb, 0x0e, 0x11, 0x78, 0xdb, 0x3e, 0x88, 0x48, 0x78, 0x68, - 0x05, 0x21, 0x13, 0x0c, 0x2d, 0x71, 0xb7, 0x6f, 0x49, 0xd9, 0x52, 0xb2, 0x71, 0xcb, 0x63, 0x1e, - 0x93, 0xaa, 0x1d, 0xff, 0x95, 0x18, 0x8d, 0x15, 0x8f, 0x31, 0x6f, 0x40, 0x6c, 0x1c, 0x50, 0x1b, - 0xfb, 0x3e, 0x13, 0x58, 0x50, 0xe6, 0x73, 0xa5, 0xae, 0x4d, 0x4e, 0x19, 0xe1, 0x01, 0x75, 0xb1, - 0x60, 0xa1, 0xb2, 0x34, 0x54, 0x03, 0xf9, 0xcb, 0x89, 0x3e, 0xd8, 0x82, 0x0e, 0x09, 0x17, 0x78, - 0x18, 0x24, 0x06, 0xb3, 0x06, 0x97, 0x5f, 0xc5, 0x64, 0x6f, 0xd2, 0x42, 0xde, 0x21, 0x07, 0x11, - 0xe1, 0xc2, 0x7c, 0x0f, 0x6f, 0x4f, 0x28, 0x3c, 0x60, 0x3e, 0x27, 0xa8, 0x0d, 0x61, 0x36, 0x88, - 0xd7, 0x40, 0x73, 0xb6, 0xb5, 0xb0, 0xb3, 0x62, 0x4d, 0x2c, 0x65, 0x65, 0xa5, 0xed, 0x2b, 0x27, - 0x3f, 0x1b, 0x95, 0x4e, 0xae, 0xca, 0xdc, 0x83, 0x35, 0xd9, 0x7e, 0x37, 0xae, 0xd8, 0x75, 0xdd, - 0x90, 0xf0, 0x74, 0x34, 0xda, 0x84, 0x4b, 0x99, 0xb3, 0x8b, 0x13, 0xad, 0x06, 0x9a, 0xa0, 0x75, - 0xad, 0x73, 0x23, 0x13, 0x54, 0x8d, 0xf9, 0x04, 0xde, 0xd1, 0x34, 0x52, 0xa4, 0xeb, 0x70, 0x51, - 0x22, 0x5d, 0xe8, 0x52, 0xc5, 0x39, 0xb3, 0x69, 0x28, 0x94, 0x97, 0x21, 0x1b, 0x11, 0xff, 0x39, - 0xa1, 0x5e, 0x4f, 0xa4, 0xaf, 0x90, 0x76, 0x2f, 0x6a, 0xe7, 0xdd, 0x03, 0xf9, 0xff, 0x6e, 0x4f, - 0x0a, 0xb2, 0xfb, 0x6c, 0xa7, 0x1a, 0xe4, 0xcc, 0x26, 0x87, 0x37, 0xdb, 0x03, 0xb6, 0xdf, 0x7f, - 0x4b, 0x45, 0xef, 0xd9, 0xa7, 0x80, 0x86, 0xf2, 0x86, 0x68, 0x19, 0xce, 0x17, 0x8a, 0xd4, 0x2f, - 0xf4, 0x14, 0x42, 0x92, 0xb9, 0x6a, 0x33, 0x4d, 0xd0, 0x5a, 0xd8, 0x31, 0xac, 0xe4, 0x8c, 0x56, - 0x7a, 0x46, 0xeb, 0x75, 0x7a, 0xc6, 0xf6, 0xd5, 0xf8, 0x65, 0x8f, 0x7e, 0x35, 0x40, 0x27, 0x57, - 0x67, 0xde, 0x4d, 0xb1, 0x89, 0xef, 0x52, 0xdf, 0x93, 0x00, 0xd9, 0x65, 0xfb, 0xd0, 0xd0, 0x89, - 0x6a, 0xa9, 0x17, 0xf0, 0x7a, 0x90, 0x08, 0x5d, 0x47, 0x2a, 0xea, 0xc0, 0xf7, 0x35, 0x07, 0xd6, - 0x2c, 0xd6, 0x59, 0x0c, 0xf2, 0x6d, 0x33, 0x12, 0xe9, 0x20, 0x6e, 0x91, 0xe4, 0x1b, 0x50, 0x28, - 0x17, 0x54, 0x85, 0xb2, 0x07, 0xab, 0xfb, 0x51, 0x18, 0x12, 0x5f, 0x74, 0xe3, 0xef, 0x56, 0xbe, - 0xd4, 0xb4, 0xaf, 0xb1, 0xa0, 0x2a, 0x63, 0x2d, 0xde, 0x89, 0x24, 0x13, 0xd2, 0x9d, 0x66, 0xfe, - 0x6f, 0x27, 0x92, 0xe7, 0xdb, 0xf9, 0x3b, 0x07, 0xe7, 0x24, 0x36, 0xfa, 0x02, 0x20, 0x3c, 0x0f, - 0x08, 0xda, 0xd0, 0xf4, 0xd3, 0xc7, 0xcb, 0x78, 0x38, 0x8d, 0x35, 0x79, 0x07, 0xf3, 0xde, 0xe7, - 0xef, 0x7f, 0x8e, 0x67, 0x1a, 0x68, 0x35, 0x49, 0xbb, 0x33, 0x60, 0xce, 0x64, 0xe2, 0x39, 0x3a, - 0x06, 0xb0, 0x9a, 0x4f, 0x01, 0xda, 0x2c, 0x9b, 0xa1, 0x09, 0x9d, 0xf1, 0x68, 0x3a, 0xb3, 0x42, - 0x6a, 0x49, 0x24, 0x13, 0x35, 0x35, 0x48, 0x85, 0xc4, 0x49, 0xaa, 0x7c, 0x7a, 0xca, 0xa9, 0x34, - 0xf9, 0x2b, 0xa7, 0xd2, 0x05, 0xf2, 0x52, 0xaa, 0x42, 0x52, 0xd1, 0x57, 0x00, 0x17, 0x0b, 0xdf, - 0x3f, 0x2a, 0x9f, 0xa4, 0xc9, 0x90, 0xb1, 0x35, 0xa5, 0x5b, 0x81, 0x6d, 0x48, 0xb0, 0x75, 0xb4, - 0xa6, 0x03, 0x2b, 0xa4, 0x4d, 0x92, 0x15, 0xe2, 0x50, 0x4e, 0xa6, 0xcb, 0x54, 0x39, 0x99, 0x36, - 0x63, 0x97, 0x92, 0x15, 0x33, 0xd3, 0xde, 0x3d, 0x39, 0xab, 0x83, 0xd3, 0xb3, 0x3a, 0xf8, 0x7d, - 0x56, 0x07, 0x47, 0xe3, 0x7a, 0xe5, 0x74, 0x5c, 0xaf, 0xfc, 0x18, 0xd7, 0x2b, 0xef, 0x1e, 0x78, - 0x54, 0xf4, 0x22, 0xc7, 0xda, 0x67, 0x43, 0x7b, 0x44, 0xc5, 0x47, 0x2a, 0x92, 0x6e, 0x5b, 0x2e, - 0xde, 0x1a, 0x32, 0x37, 0x1a, 0x10, 0x5b, 0x1c, 0x06, 0x84, 0x3b, 0xf3, 0x32, 0xb3, 0x8f, 0xff, - 0x05, 0x00, 0x00, 0xff, 0xff, 0x00, 0x17, 0x5c, 0x23, 0x21, 0x07, 0x00, 0x00, + // 740 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0x41, 0x4f, 0xd4, 0x40, + 0x14, 0xc7, 0xb7, 0x20, 0xa8, 0xc3, 0x62, 0x60, 0x34, 0xb8, 0x56, 0xd8, 0x85, 0x12, 0x14, 0x44, + 0x5a, 0xc1, 0x83, 0x57, 0xd9, 0x68, 0xf0, 0xa2, 0xd1, 0x62, 0x34, 0x31, 0x31, 0x9b, 0x29, 0x1d, + 0xbb, 0xcd, 0x76, 0x3b, 0xa5, 0x33, 0x5d, 0xe1, 0xea, 0xd1, 0x13, 0x09, 0x07, 0xe3, 0xd5, 0xcf, + 0xe0, 0x87, 0xe0, 0x48, 0xe2, 0xc5, 0x93, 0x1a, 0xf0, 0x83, 0x98, 0x4e, 0xa7, 0xa5, 0xdd, 0x9d, + 0x6e, 0xd6, 0x5b, 0xa7, 0xff, 0xf7, 0xfe, 0xf3, 0x7b, 0x33, 0xf3, 0x1e, 0x58, 0xa0, 0x76, 0xc7, + 0x40, 0x3d, 0xe4, 0x7a, 0x46, 0x6f, 0xd3, 0xc2, 0x0c, 0x6d, 0x1a, 0xfb, 0x11, 0x0e, 0x0f, 0xf5, + 0x20, 0x24, 0x8c, 0xc0, 0x59, 0x6a, 0x77, 0x74, 0x2e, 0xeb, 0x42, 0x56, 0x6f, 0x38, 0xc4, 0x21, + 0x5c, 0x35, 0xe2, 0xaf, 0x24, 0x50, 0x9d, 0x77, 0x08, 0x71, 0x3c, 0x6c, 0xa0, 0xc0, 0x35, 0x90, + 0xef, 0x13, 0x86, 0x98, 0x4b, 0x7c, 0x2a, 0xd4, 0xa5, 0xc1, 0x5d, 0x7a, 0xc8, 0x73, 0x6d, 0xc4, + 0x48, 0x28, 0x42, 0x1a, 0xc2, 0x80, 0xaf, 0xac, 0xe8, 0x83, 0xc1, 0xdc, 0x2e, 0xa6, 0x0c, 0x75, + 0x03, 0x11, 0xa0, 0x0e, 0x7a, 0xb0, 0x83, 0x44, 0xd3, 0x5e, 0x80, 0xf9, 0x57, 0x31, 0xf5, 0x6e, + 0x64, 0x75, 0x5d, 0xd6, 0xf4, 0x88, 0xb5, 0xcb, 0x10, 0x8b, 0xa8, 0x89, 0xf7, 0x23, 0x4c, 0x19, + 0xd4, 0xc1, 0x44, 0x88, 0x7c, 0x07, 0xd7, 0x94, 0x45, 0x65, 0x75, 0x6a, 0xab, 0xa6, 0x0f, 0x94, + 0xa5, 0x9b, 0xb1, 0x6e, 0x26, 0x61, 0xda, 0x23, 0xb0, 0x50, 0xe2, 0x47, 0x03, 0xe2, 0x53, 0x0c, + 0xe7, 0xc0, 0x24, 0xe5, 0x7f, 0xb8, 0xe3, 0x55, 0x53, 0xac, 0xb4, 0x1a, 0x98, 0xe3, 0x89, 0x6f, + 0xd2, 0xea, 0x52, 0x04, 0xed, 0x3d, 0xb8, 0x39, 0xa0, 0x08, 0xb3, 0x26, 0x00, 0xd9, 0x69, 0xc4, + 0x86, 0xe3, 0xab, 0x53, 0x5b, 0xf3, 0x12, 0xc4, 0x2c, 0xb5, 0x79, 0xe9, 0xe4, 0x57, 0xa3, 0x62, + 0xe6, 0xb2, 0xb4, 0x1d, 0x50, 0xe3, 0xf6, 0xdb, 0x71, 0xc6, 0xb6, 0x6d, 0x87, 0x98, 0x66, 0xd5, + 0xaf, 0x83, 0xd9, 0x2c, 0xb2, 0x85, 0x12, 0x4d, 0x70, 0xcf, 0x64, 0x82, 0xc8, 0xd1, 0x1e, 0x83, + 0x5b, 0x12, 0x23, 0x41, 0xba, 0x0c, 0xa6, 0x39, 0x52, 0x9f, 0x4b, 0x15, 0xe5, 0x82, 0x35, 0x55, + 0xa0, 0xbc, 0x0c, 0x49, 0x0f, 0xfb, 0xcf, 0xb0, 0xeb, 0xb4, 0x59, 0x7a, 0x0a, 0xa9, 0x7b, 0x51, + 0xbb, 0x70, 0x0f, 0xf8, 0xff, 0x56, 0x9b, 0x0b, 0xdc, 0x7d, 0xdc, 0xac, 0x06, 0xb9, 0x60, 0x8d, + 0x82, 0xeb, 0x4d, 0x8f, 0xec, 0x75, 0xde, 0xba, 0xac, 0xfd, 0xf4, 0x20, 0x70, 0x43, 0xfe, 0xd0, + 0xe2, 0x0b, 0x29, 0x24, 0x89, 0x15, 0x7c, 0x02, 0x00, 0xce, 0xa2, 0x6a, 0x63, 0xfc, 0xfa, 0x55, + 0x3d, 0x79, 0x6b, 0x7a, 0xfa, 0xd6, 0xf4, 0xd7, 0xe9, 0x5b, 0x6b, 0x5e, 0x89, 0x4f, 0xf6, 0xe8, + 0x77, 0x43, 0x31, 0x73, 0x79, 0xda, 0xed, 0x14, 0x1b, 0xfb, 0xb6, 0xeb, 0x3b, 0x1c, 0x20, 0xbb, + 0xd9, 0x0e, 0x50, 0x65, 0xa2, 0x28, 0xea, 0x39, 0xb8, 0x16, 0x24, 0x42, 0xcb, 0xe2, 0x8a, 0xb8, + 0xe0, 0x3b, 0x92, 0x0b, 0x96, 0x14, 0x66, 0x4e, 0x07, 0x79, 0xdb, 0x8c, 0x84, 0x47, 0x60, 0xbb, + 0x48, 0xf2, 0x5d, 0x11, 0x28, 0x7d, 0xaa, 0x40, 0xd9, 0x01, 0xd5, 0xbd, 0x28, 0x0c, 0xb1, 0xcf, + 0x5a, 0x71, 0x73, 0x89, 0x66, 0x18, 0xed, 0x34, 0xa6, 0x44, 0x66, 0xac, 0xc5, 0x35, 0xe1, 0x64, + 0x87, 0xb4, 0xa6, 0xb1, 0xff, 0xab, 0x09, 0xe7, 0xf9, 0xb6, 0xbe, 0x5e, 0x06, 0x13, 0x1c, 0x1b, + 0x7e, 0x53, 0xc0, 0x4c, 0x7f, 0xcf, 0x41, 0x43, 0xe2, 0x3a, 0xac, 0xdb, 0xd5, 0x07, 0xa3, 0x27, + 0x24, 0x27, 0xa3, 0xad, 0x7f, 0xfa, 0xf1, 0xf7, 0x78, 0x6c, 0x05, 0x2e, 0x27, 0x03, 0xc6, 0xf2, + 0x88, 0x95, 0x0d, 0x19, 0xda, 0xcf, 0xf3, 0x59, 0x01, 0xe0, 0xa2, 0x8b, 0xe1, 0x5a, 0xd9, 0x6e, + 0x03, 0x33, 0x40, 0xbd, 0x37, 0x4a, 0xa8, 0x40, 0x5a, 0xe1, 0x48, 0x0d, 0xb8, 0x20, 0x41, 0xba, + 0xe8, 0x7b, 0x78, 0xac, 0x80, 0x6a, 0xbe, 0x55, 0xe1, 0x7a, 0xd9, 0x1e, 0x92, 0xc9, 0xa0, 0xde, + 0x1f, 0x2d, 0x58, 0x20, 0xad, 0x72, 0x24, 0x0d, 0x2e, 0x4a, 0x90, 0x0a, 0x63, 0x81, 0x53, 0xe5, + 0x5b, 0xbc, 0x9c, 0x4a, 0x32, 0x24, 0xca, 0xa9, 0x64, 0x53, 0x63, 0x28, 0x55, 0x61, 0x9c, 0xc0, + 0x2f, 0x0a, 0x98, 0x2e, 0x34, 0x29, 0x2c, 0xdf, 0x49, 0xd2, 0xe8, 0xea, 0xc6, 0x88, 0xd1, 0x02, + 0x6c, 0x8d, 0x83, 0x2d, 0xc3, 0x25, 0x19, 0x58, 0x61, 0x24, 0x70, 0xb2, 0x42, 0xcf, 0x96, 0x93, + 0xc9, 0x1a, 0xbf, 0x9c, 0x4c, 0x3a, 0x08, 0x86, 0x92, 0x15, 0x1b, 0xbb, 0xb9, 0x7d, 0x72, 0x56, + 0x57, 0x4e, 0xcf, 0xea, 0xca, 0x9f, 0xb3, 0xba, 0x72, 0x74, 0x5e, 0xaf, 0x9c, 0x9e, 0xd7, 0x2b, + 0x3f, 0xcf, 0xeb, 0x95, 0x77, 0x77, 0x1d, 0x97, 0xb5, 0x23, 0x4b, 0xdf, 0x23, 0x5d, 0xa3, 0xe7, + 0xb2, 0x8f, 0x2e, 0x4b, 0xdc, 0x36, 0x6c, 0xb4, 0xd1, 0x25, 0x76, 0xe4, 0x61, 0x83, 0x1d, 0x06, + 0x98, 0x5a, 0x93, 0x7c, 0xb0, 0x3c, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, 0x67, 0xde, 0x72, 0xab, + 0x6b, 0x08, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -579,11 +678,17 @@ const _ = grpc.SupportPackageIsVersion4 // // 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 { + // submit Blob Status + SubmitBlobStatus(ctx context.Context, in *QuerySubmitBlobStatusRequest, opts ...grpc.CallOption) (*QuerySubmitBlobStatusResponse, error) // Validators returns registered validators of the module. Validators(ctx context.Context, in *QueryValidatorsRequest, opts ...grpc.CallOption) (*QueryValidatorsResponse, error) + // Todo: will be removed AvailAddress(ctx context.Context, in *QueryAvailAddressRequest, opts ...grpc.CallOption) (*QueryAvailAddressResponse, error) + // proven height ProvenHeight(ctx context.Context, in *QueryProvenHeightRequest, opts ...grpc.CallOption) (*QueryProvenHeightResponse, error) + // pending blocks PendingBlocks(ctx context.Context, in *QueryPendingBlocksRequest, opts ...grpc.CallOption) (*QueryPendingBlocksResponse, error) + // expired blocks ExpiredBlocks(ctx context.Context, in *QueryExpiredBlocksRequest, opts ...grpc.CallOption) (*QueryExpiredBlocksResponse, error) } @@ -595,6 +700,15 @@ func NewQueryClient(cc grpc1.ClientConn) QueryClient { return &queryClient{cc} } +func (c *queryClient) SubmitBlobStatus(ctx context.Context, in *QuerySubmitBlobStatusRequest, opts ...grpc.CallOption) (*QuerySubmitBlobStatusResponse, error) { + out := new(QuerySubmitBlobStatusResponse) + err := c.cc.Invoke(ctx, "/sdk.avail.v1beta1.Query/SubmitBlobStatus", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *queryClient) Validators(ctx context.Context, in *QueryValidatorsRequest, opts ...grpc.CallOption) (*QueryValidatorsResponse, error) { out := new(QueryValidatorsResponse) err := c.cc.Invoke(ctx, "/sdk.avail.v1beta1.Query/Validators", in, out, opts...) @@ -642,11 +756,17 @@ func (c *queryClient) ExpiredBlocks(ctx context.Context, in *QueryExpiredBlocksR // QueryServer is the server API for Query service. type QueryServer interface { + // submit Blob Status + SubmitBlobStatus(context.Context, *QuerySubmitBlobStatusRequest) (*QuerySubmitBlobStatusResponse, error) // Validators returns registered validators of the module. Validators(context.Context, *QueryValidatorsRequest) (*QueryValidatorsResponse, error) + // Todo: will be removed AvailAddress(context.Context, *QueryAvailAddressRequest) (*QueryAvailAddressResponse, error) + // proven height ProvenHeight(context.Context, *QueryProvenHeightRequest) (*QueryProvenHeightResponse, error) + // pending blocks PendingBlocks(context.Context, *QueryPendingBlocksRequest) (*QueryPendingBlocksResponse, error) + // expired blocks ExpiredBlocks(context.Context, *QueryExpiredBlocksRequest) (*QueryExpiredBlocksResponse, error) } @@ -654,6 +774,9 @@ type QueryServer interface { type UnimplementedQueryServer struct { } +func (*UnimplementedQueryServer) SubmitBlobStatus(ctx context.Context, req *QuerySubmitBlobStatusRequest) (*QuerySubmitBlobStatusResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SubmitBlobStatus not implemented") +} func (*UnimplementedQueryServer) Validators(ctx context.Context, req *QueryValidatorsRequest) (*QueryValidatorsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Validators not implemented") } @@ -674,6 +797,24 @@ func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) } +func _Query_SubmitBlobStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QuerySubmitBlobStatusRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).SubmitBlobStatus(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/sdk.avail.v1beta1.Query/SubmitBlobStatus", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).SubmitBlobStatus(ctx, req.(*QuerySubmitBlobStatusRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _Query_Validators_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryValidatorsRequest) if err := dec(in); err != nil { @@ -768,6 +909,10 @@ var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "sdk.avail.v1beta1.Query", HandlerType: (*QueryServer)(nil), Methods: []grpc.MethodDesc{ + { + MethodName: "SubmitBlobStatus", + Handler: _Query_SubmitBlobStatus_Handler, + }, { MethodName: "Validators", Handler: _Query_Validators_Handler, @@ -793,6 +938,71 @@ var _Query_serviceDesc = grpc.ServiceDesc{ Metadata: "sdk/avail/v1beta1/query.proto", } +func (m *QuerySubmitBlobStatusRequest) 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 *QuerySubmitBlobStatusRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QuerySubmitBlobStatusRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Range != nil { + { + size, err := m.Range.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QuerySubmitBlobStatusResponse) 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 *QuerySubmitBlobStatusResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QuerySubmitBlobStatusResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Status) > 0 { + i -= len(m.Status) + copy(dAtA[i:], m.Status) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Status))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + func (m *QueryValidatorsRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -984,12 +1194,12 @@ func (m *BlockWithExpiration) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Expiration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Expiration):]) - if err1 != nil { - return 0, err1 + n2, err2 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Expiration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Expiration):]) + if err2 != nil { + return 0, err2 } - i -= n1 - i = encodeVarintQuery(dAtA, i, uint64(n1)) + i -= n2 + i = encodeVarintQuery(dAtA, i, uint64(n2)) i-- dAtA[i] = 0x12 if m.Height != 0 { @@ -1117,12 +1327,12 @@ func (m *QueryExpiredBlocksResponse) MarshalToSizedBuffer(dAtA []byte) (int, err dAtA[i] = 0x12 } } - n2, err2 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.CurrentTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.CurrentTime):]) - if err2 != nil { - return 0, err2 + n3, err3 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.CurrentTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.CurrentTime):]) + if err3 != nil { + return 0, err3 } - i -= n2 - i = encodeVarintQuery(dAtA, i, uint64(n2)) + i -= n3 + i = encodeVarintQuery(dAtA, i, uint64(n3)) i-- dAtA[i] = 0xa return len(dAtA) - i, nil @@ -1139,6 +1349,32 @@ func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } +func (m *QuerySubmitBlobStatusRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Range != nil { + l = m.Range.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QuerySubmitBlobStatusResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Status) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + func (m *QueryValidatorsRequest) Size() (n int) { if m == nil { return 0 @@ -1280,6 +1516,174 @@ func sovQuery(x uint64) (n int) { func sozQuery(x uint64) (n int) { return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (m *QuerySubmitBlobStatusRequest) 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: QuerySubmitBlobStatusRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QuerySubmitBlobStatusRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Range", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Range == nil { + m.Range = &Range{} + } + if err := m.Range.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + 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 (m *QuerySubmitBlobStatusResponse) 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: QuerySubmitBlobStatusResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QuerySubmitBlobStatusResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", 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.Status = 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 (m *QueryValidatorsRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 diff --git a/types/query.pb.gw.go b/types/query.pb.gw.go index a10c610..ab4ef83 100644 --- a/types/query.pb.gw.go +++ b/types/query.pb.gw.go @@ -33,6 +33,42 @@ var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join +var ( + filter_Query_SubmitBlobStatus_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Query_SubmitBlobStatus_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QuerySubmitBlobStatusRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SubmitBlobStatus_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.SubmitBlobStatus(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_SubmitBlobStatus_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QuerySubmitBlobStatusRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SubmitBlobStatus_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.SubmitBlobStatus(ctx, &protoReq) + return msg, metadata, err + +} + func request_Query_Validators_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq QueryValidatorsRequest var metadata runtime.ServerMetadata @@ -147,6 +183,29 @@ func local_request_Query_ExpiredBlocks_0(ctx context.Context, marshaler runtime. // 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_SubmitBlobStatus_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_SubmitBlobStatus_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_SubmitBlobStatus_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + mux.Handle("GET", pattern_Query_Validators_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -303,6 +362,26 @@ func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc // "QueryClient" to call the correct interceptors. func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { + mux.Handle("GET", pattern_Query_SubmitBlobStatus_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_SubmitBlobStatus_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_SubmitBlobStatus_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + mux.Handle("GET", pattern_Query_Validators_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -407,6 +486,8 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } var ( + pattern_Query_SubmitBlobStatus_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"availblob", "v1beta1", "submitBlobStatus"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_Validators_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"availblob", "v1beta1", "validators"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_AvailAddress_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"availblob", "v1beta1", "avail_address"}, "", runtime.AssumeColonVerbOpt(false))) @@ -419,6 +500,8 @@ var ( ) var ( + forward_Query_SubmitBlobStatus_0 = runtime.ForwardResponseMessage + forward_Query_Validators_0 = runtime.ForwardResponseMessage forward_Query_AvailAddress_0 = runtime.ForwardResponseMessage From b67260a951f0cd5626896b8ab6d43c4facd102b6 Mon Sep 17 00:00:00 2001 From: saiteja Date: Thu, 29 Aug 2024 14:46:32 +0530 Subject: [PATCH 22/58] feat: changes --- keeper/abci.go | 67 ++++++++++++++++++------------------------------ keeper/keeper.go | 48 ++++++++++++++++++++++------------ keeper/store.go | 46 ++++++++++++++++++++++++++------- keys.go | 4 +++ 4 files changed, 97 insertions(+), 68 deletions(-) diff --git a/keeper/abci.go b/keeper/abci.go index 59227b6..6ee9877 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -1,11 +1,10 @@ package keeper import ( - "fmt" + "bytes" abci "github.com/cometbft/cometbft/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/vitwit/avail-da-module/types" ) type ProofOfBlobProposalHandler struct { @@ -35,61 +34,45 @@ func (h *ProofOfBlobProposalHandler) PrepareProposal(ctx sdk.Context, req *abci. return nil, err } - // var latestProvenHeight int64 = 1 - // // TODO : set latestproven height in store - // injectData := h.keeper.prepareInjectData(ctx, req.Time, latestProvenHeight) - // injectDataBz := h.keeper.marshalMaxBytes(&injectData, req.MaxTxBytes, latestProvenHeight) - // resp.Txs = h.keeper.addAvailblobDataToTxs(injectDataBz, req.MaxTxBytes, resp.Txs) - return resp, nil } func (h *ProofOfBlobProposalHandler) ProcessProposal(ctx sdk.Context, req *abci.RequestProcessProposal) (*abci.ResponseProcessProposal, error) { - // // fmt.Println("length of transactions: ", len(req.Txs), ctx.BlockHeight()) - // injectedData := h.keeper.getInjectedData(req.Txs) - // if injectedData != nil { - // req.Txs = req.Txs[1:] // Pop the injected data for the default handler - - // if err := h.keeper.processPendingBlocks(ctx, req.Time, &injectedData.PendingBlocks); err != nil { - // return nil, err - // } - // } return h.processProposalHandler(ctx, req) } func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { - submitBlobRequest, ok := k.relayer.NextBlocksToSumbit(ctx) - if !ok { + + currentBlockHeight := ctx.BlockHeight() + if k.IsValidBlockToPostTODA(uint64(currentBlockHeight)) { return nil } - go func() { - err := k.SubmitBlobTx(ctx, submitBlobRequest) - fmt.Println("submit blob tx error.............", err) - if err == nil { - // send the blobs tx data to avail DA - } - }() + fromHeight := k.GetProvenHeightFromStore(ctx) //Todo: change this get from ProvenHeight from store + endHeight := min(fromHeight+uint64(k.MaxBlocksForBlob), uint64(ctx.BlockHeight())) - return nil + sdkCtx := sdk.UnwrapSDKContext(ctx) + k.SetBlobStatusPending(sdkCtx, fromHeight, endHeight) - // injectDataBz := k.marshalMaxBytes(&injectedData, int64(req.Size()), req.Height) - // _ = k.addAvailblobDataToTxs(injectDataBz, int64(req.Size()), req.Txs) + // only proposar should should run the this + if bytes.Equal(req.ProposerAddress, k.proposerAddress) { - // if err := k.preblockerPendingBlocks(ctx, req.Time, req.ProposerAddress, &injectedData.PendingBlocks); err != nil { - // return err - // } - // // } - // return nil -} + // Todo: run the relayer routine + // relayer doesn't have to make submitBlob Transaction, it should just start DA submissio -func (k *Keeper) getInjectedData(txs [][]byte) *types.InjectedData { - if len(txs) != 0 { - var injectedData types.InjectedData - err := k.cdc.Unmarshal(txs[0], &injectedData) - if err == nil { - return &injectedData - } } + return nil } + +func (k *Keeper) IsValidBlockToPostTODA(height uint64) bool { + if uint64(height) <= uint64(1) { + return false + } + + if (height-1)%k.PublishToAvailBlockInterval != 0 { + return false + } + + return true +} diff --git a/keeper/keeper.go b/keeper/keeper.go index e32c902..70b33b9 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -1,8 +1,8 @@ package keeper import ( + "encoding/binary" "errors" - "fmt" "cosmossdk.io/collections" storetypes2 "cosmossdk.io/store/types" @@ -39,6 +39,8 @@ type Keeper struct { cdc codec.BinaryCodec publishToAvailBlockInterval int + PublishToAvailBlockInterval uint64 + MaxBlocksForBlob uint injectedProofsLimit int app_id int @@ -78,7 +80,9 @@ func NewKeeper( publishToAvailBlockInterval: publishToAvailBlockInterval, app_id: appId, - unprovenBlocks: make(map[int64][]byte), + unprovenBlocks: make(map[int64][]byte), + MaxBlocksForBlob: 10, //Todo: call this from app.go, later change to params + PublishToAvailBlockInterval: 5, //Todo: call this from app.go, later change to params } } @@ -86,27 +90,37 @@ func (k *Keeper) SetRelayer(r *relayer.Relayer) { k.relayer = r } -func (k *Keeper) SubmitBlob(ctx sdk.Context, req *types.MsgSubmitBlobRequest) (*types.MsgSubmitBlobResponse, error) { +func (k *Keeper) SetBlobStatusPending(ctx sdk.Context, provenHeight, endHeight uint64) error { + store := ctx.KVStore(k.storeKey) - if IsAlreadyExist(ctx, store, *req.BlocksRange) { - return &types.MsgSubmitBlobResponse{}, errors.New("the range is already processed") + + if IsStateReady(store) { //TOodo: we should check for expiration too + return errors.New("a block range with same start height is already being processed") } - err := updateBlobStatus(ctx, store, *req.BlocksRange, PENDING) - fmt.Println("errr.........", err) - return &types.MsgSubmitBlobResponse{}, err + UpdateBlobStatus(ctx, store, PENDING_STATE) + UpdateEndHeight(ctx, store, endHeight) + return nil } -func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatusRequest) (*types.MsgUpdateBlobStatusResponse, error) { +func (k *Keeper) GetProvenHeightFromStore(ctx sdk.Context) uint64 { store := ctx.KVStore(k.storeKey) - if !IsAlreadyExist(ctx, store, *req.BlocksRange) { - return &types.MsgUpdateBlobStatusResponse{}, errors.New("the range does not exist") + heightBytes := store.Get(availblob1.ProvenHeightKey) + if heightBytes == nil || len(heightBytes) == 0 { + return 0 } - status := FAILURE - if req.IsSuccess { - status = SUCCESS - } - err := updateBlobStatus(ctx, store, *req.BlocksRange, status) - return &types.MsgUpdateBlobStatusResponse{}, err + provenHeight := binary.BigEndian.Uint64(heightBytes) + return provenHeight +} + +// Todo: remove this method later +func (k *Keeper) SubmitBlob(ctx sdk.Context, req *types.MsgSubmitBlobRequest) (*types.MsgSubmitBlobResponse, error) { + + return &types.MsgSubmitBlobResponse{}, nil +} + +func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatusRequest) (*types.MsgUpdateBlobStatusResponse, error) { + //Todo: status should be changed to Voting or Ready, depending on the request + return &types.MsgUpdateBlobStatusResponse{}, nil } diff --git a/keeper/store.go b/keeper/store.go index a49d5bf..dbdbd40 100644 --- a/keeper/store.go +++ b/keeper/store.go @@ -3,7 +3,6 @@ package keeper import ( "context" "encoding/binary" - "errors" "fmt" storetypes2 "cosmossdk.io/store/types" @@ -12,9 +11,10 @@ import ( ) const ( - PENDING uint32 = 0 - SUCCESS uint32 = 1 - FAILURE uint32 = 2 + READY_STATE uint32 = 0 + PENDING_STATE uint32 = 1 + IN_VOTING_STATE uint32 = 2 + FAILURE_STATE uint32 = 3 ) func IsAlreadyExist(ctx context.Context, store storetypes2.KVStore, blocksRange types.Range) bool { @@ -27,16 +27,44 @@ func IsAlreadyExist(ctx context.Context, store storetypes2.KVStore, blocksRange return true } -func updateBlobStatus(ctx context.Context, store storetypes2.KVStore, blocksRange types.Range, status uint32) error { - if status != PENDING && status != SUCCESS && status != FAILURE { - return errors.New("unknown status") +func IsStateReady(store storetypes2.KVStore) bool { + statusBytes := store.Get(availblob1.BlobStatusKey) + if statusBytes == nil || len(statusBytes) == 0 { + return true } - pendingBlobStoreKey := availblob1.PendingBlobsStoreKey(blocksRange) + + status := binary.BigEndian.Uint32(statusBytes) + + return status == READY_STATE + +} + +func UpdateBlobStatus(ctx context.Context, store storetypes2.KVStore, status uint32) error { statusBytes := make([]byte, 4) binary.BigEndian.PutUint32(statusBytes, status) - store.Set(pendingBlobStoreKey, statusBytes) + store.Set(availblob1.BlobStatusKey, statusBytes) + return nil +} + +func UpdateEndHeight(ctx context.Context, store storetypes2.KVStore, endHeight uint64) error { + + heightBytes := make([]byte, 8) + + binary.BigEndian.PutUint64(heightBytes, endHeight) + + store.Set(availblob1.NextHeightKey, heightBytes) + return nil +} + +func UpdateProvenHeight(ctx context.Context, store storetypes2.KVStore, endHeight uint64) error { + + heightBytes := make([]byte, 8) + + binary.BigEndian.PutUint64(heightBytes, endHeight) + + store.Set(availblob1.ProvenHeightKey, heightBytes) return nil } diff --git a/keys.go b/keys.go index 641f2bd..90e5e5a 100644 --- a/keys.go +++ b/keys.go @@ -28,6 +28,10 @@ var ( ClientStoreKey = []byte("client_store/") PendingBlobsKey = collections.NewPrefix(5) + + BlobStatusKey = collections.NewPrefix(6) + + NextHeightKey = collections.NewPrefix(7) ) const ( From bba689d246d2c3546cd7e9d25f35eb4b22c36717 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Fri, 30 Aug 2024 17:23:42 +0530 Subject: [PATCH 23/58] handle error --- keeper/abci.go | 18 +++++++++++++++--- keeper/keeper.go | 42 +++++++++++++++++++++++++++++++++++++----- keeper/store.go | 12 ++++++------ 3 files changed, 58 insertions(+), 14 deletions(-) diff --git a/keeper/abci.go b/keeper/abci.go index 6ee9877..7d69e36 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -2,6 +2,7 @@ package keeper import ( "bytes" + "fmt" abci "github.com/cometbft/cometbft/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -42,6 +43,7 @@ func (h *ProofOfBlobProposalHandler) ProcessProposal(ctx sdk.Context, req *abci. } func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { + fmt.Println("coming hereee.........", req) currentBlockHeight := ctx.BlockHeight() if k.IsValidBlockToPostTODA(uint64(currentBlockHeight)) { @@ -49,17 +51,27 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err } fromHeight := k.GetProvenHeightFromStore(ctx) //Todo: change this get from ProvenHeight from store + fmt.Println("from height..", fromHeight) endHeight := min(fromHeight+uint64(k.MaxBlocksForBlob), uint64(ctx.BlockHeight())) + fmt.Println("end height..", endHeight) sdkCtx := sdk.UnwrapSDKContext(ctx) - k.SetBlobStatusPending(sdkCtx, fromHeight, endHeight) + err := k.SetBlobStatusPending(sdkCtx, fromHeight, endHeight) + if err != nil { + fmt.Println("error while setting blob status...", err) + } // only proposar should should run the this if bytes.Equal(req.ProposerAddress, k.proposerAddress) { + // update blob status to success - // Todo: run the relayer routine - // relayer doesn't have to make submitBlob Transaction, it should just start DA submissio + err = k.SetBlobStatusSuccess(sdkCtx, fromHeight, endHeight) + if err != nil { + return nil + } + // Todo: run the relayer routine + // relayer doesn't have to make submitBlob Transaction, it should just start DA submission } return nil diff --git a/keeper/keeper.go b/keeper/keeper.go index 70b33b9..a19617d 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -2,7 +2,7 @@ package keeper import ( "encoding/binary" - "errors" + "fmt" "cosmossdk.io/collections" storetypes2 "cosmossdk.io/store/types" @@ -94,23 +94,39 @@ func (k *Keeper) SetBlobStatusPending(ctx sdk.Context, provenHeight, endHeight u store := ctx.KVStore(k.storeKey) - if IsStateReady(store) { //TOodo: we should check for expiration too - return errors.New("a block range with same start height is already being processed") - } + // if IsStateReady(store) { //TOodo: we should check for expiration too + // return errors.New("a block range with same start height is already being processed") + // } UpdateBlobStatus(ctx, store, PENDING_STATE) UpdateEndHeight(ctx, store, endHeight) return nil } +func (k *Keeper) SetBlobStatusSuccess(ctx sdk.Context, provenHeight, endHeight uint64) error { + + store := ctx.KVStore(k.storeKey) + + // if IsStateReady(store) { //TOodo: we should check for expiration too + // return errors.New("a block range with same start height is already being processed") + // } + + UpdateBlobStatus(ctx, store, READY_STATE) + UpdateEndHeight(ctx, store, endHeight) + return nil +} + func (k *Keeper) GetProvenHeightFromStore(ctx sdk.Context) uint64 { store := ctx.KVStore(k.storeKey) heightBytes := store.Get(availblob1.ProvenHeightKey) - if heightBytes == nil || len(heightBytes) == 0 { + if heightBytes == nil || len(heightBytes) == 8 { return 0 } + fmt.Println("heoght buyessssssss from......", heightBytes) + provenHeight := binary.BigEndian.Uint64(heightBytes) + fmt.Println("proven height here............", provenHeight) return provenHeight } @@ -124,3 +140,19 @@ func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatu //Todo: status should be changed to Voting or Ready, depending on the request return &types.MsgUpdateBlobStatusResponse{}, nil } + +func (k *Keeper) CheckHeight(endHeight uint64) error { + // Step 1: Encode 41 into a byte slice + // var endHeight uint64 = 41 + heightBytes := make([]byte, 8) + binary.BigEndian.PutUint64(heightBytes, endHeight) + + fmt.Println("Encoded byte slice for 41:", heightBytes) + + // Step 2: Decode the byte slice back to a uint64 + decodedHeight := binary.BigEndian.Uint64(heightBytes) + + fmt.Println("Decoded height:", decodedHeight) + + return nil +} diff --git a/keeper/store.go b/keeper/store.go index dbdbd40..e034687 100644 --- a/keeper/store.go +++ b/keeper/store.go @@ -1,11 +1,11 @@ package keeper import ( - "context" "encoding/binary" "fmt" storetypes2 "cosmossdk.io/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" availblob1 "github.com/vitwit/avail-da-module" "github.com/vitwit/avail-da-module/types" ) @@ -17,7 +17,7 @@ const ( FAILURE_STATE uint32 = 3 ) -func IsAlreadyExist(ctx context.Context, store storetypes2.KVStore, blocksRange types.Range) bool { +func IsAlreadyExist(ctx sdk.Context, store storetypes2.KVStore, blocksRange types.Range) bool { pendingBlobStoreKey := availblob1.PendingBlobsStoreKey(blocksRange) blobStatus := store.Get(pendingBlobStoreKey) fmt.Println("blob status:", blobStatus, blobStatus == nil) @@ -29,6 +29,7 @@ func IsAlreadyExist(ctx context.Context, store storetypes2.KVStore, blocksRange func IsStateReady(store storetypes2.KVStore) bool { statusBytes := store.Get(availblob1.BlobStatusKey) + fmt.Println("status bytes............", statusBytes) if statusBytes == nil || len(statusBytes) == 0 { return true } @@ -36,10 +37,9 @@ func IsStateReady(store storetypes2.KVStore) bool { status := binary.BigEndian.Uint32(statusBytes) return status == READY_STATE - } -func UpdateBlobStatus(ctx context.Context, store storetypes2.KVStore, status uint32) error { +func UpdateBlobStatus(ctx sdk.Context, store storetypes2.KVStore, status uint32) error { statusBytes := make([]byte, 4) @@ -49,7 +49,7 @@ func UpdateBlobStatus(ctx context.Context, store storetypes2.KVStore, status uin return nil } -func UpdateEndHeight(ctx context.Context, store storetypes2.KVStore, endHeight uint64) error { +func UpdateEndHeight(ctx sdk.Context, store storetypes2.KVStore, endHeight uint64) error { heightBytes := make([]byte, 8) @@ -59,7 +59,7 @@ func UpdateEndHeight(ctx context.Context, store storetypes2.KVStore, endHeight u return nil } -func UpdateProvenHeight(ctx context.Context, store storetypes2.KVStore, endHeight uint64) error { +func UpdateProvenHeight(ctx sdk.Context, store storetypes2.KVStore, endHeight uint64) error { heightBytes := make([]byte, 8) From 0e383fbfc85443512eb7872790feca9d9346f8b7 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Mon, 2 Sep 2024 11:35:44 +0530 Subject: [PATCH 24/58] post data to da --- keeper/abci.go | 25 ++++++++++++++++++------- keeper/keeper.go | 15 ++++++++------- relayer/publish.go | 7 +++++++ relayer/submit_data.go | 2 +- 4 files changed, 34 insertions(+), 15 deletions(-) diff --git a/keeper/abci.go b/keeper/abci.go index 7d69e36..1347b41 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -43,13 +43,15 @@ func (h *ProofOfBlobProposalHandler) ProcessProposal(ctx sdk.Context, req *abci. } func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { - fmt.Println("coming hereee.........", req) + // fmt.Println("coming hereee.........", req) currentBlockHeight := ctx.BlockHeight() - if k.IsValidBlockToPostTODA(uint64(currentBlockHeight)) { + if !k.IsValidBlockToPostTODA(uint64(currentBlockHeight)) { return nil } + fmt.Println("block heighttt.........", ctx.BlockHeight()) + fromHeight := k.GetProvenHeightFromStore(ctx) //Todo: change this get from ProvenHeight from store fmt.Println("from height..", fromHeight) endHeight := min(fromHeight+uint64(k.MaxBlocksForBlob), uint64(ctx.BlockHeight())) @@ -61,17 +63,26 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err fmt.Println("error while setting blob status...", err) } + var blocksToSumit []int64 + + for i := fromHeight + 1; i < endHeight; i++ { + blocksToSumit = append(blocksToSumit, int64(i)) + } + + fmt.Println("blocks to submittttttttt.........", blocksToSumit) + // only proposar should should run the this if bytes.Equal(req.ProposerAddress, k.proposerAddress) { // update blob status to success - - err = k.SetBlobStatusSuccess(sdkCtx, fromHeight, endHeight) - if err != nil { - return nil - } + // err = k.SetBlobStatusSuccess(sdkCtx, fromHeight, endHeight) + // if err != nil { + // return nil + // } // Todo: run the relayer routine // relayer doesn't have to make submitBlob Transaction, it should just start DA submission + k.relayer.PostBlocks(ctx, blocksToSumit) + } return nil diff --git a/keeper/keeper.go b/keeper/keeper.go index a19617d..8adef6c 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -2,6 +2,7 @@ package keeper import ( "encoding/binary" + "errors" "fmt" "cosmossdk.io/collections" @@ -94,9 +95,9 @@ func (k *Keeper) SetBlobStatusPending(ctx sdk.Context, provenHeight, endHeight u store := ctx.KVStore(k.storeKey) - // if IsStateReady(store) { //TOodo: we should check for expiration too - // return errors.New("a block range with same start height is already being processed") - // } + if !IsStateReady(store) { //TOodo: we should check for expiration too + return errors.New("a block range with same start height is already being processed") + } UpdateBlobStatus(ctx, store, PENDING_STATE) UpdateEndHeight(ctx, store, endHeight) @@ -107,9 +108,9 @@ func (k *Keeper) SetBlobStatusSuccess(ctx sdk.Context, provenHeight, endHeight u store := ctx.KVStore(k.storeKey) - // if IsStateReady(store) { //TOodo: we should check for expiration too - // return errors.New("a block range with same start height is already being processed") - // } + if !IsStateReady(store) { //TOodo: we should check for expiration too + return errors.New("a block range with same start height is already being processed") + } UpdateBlobStatus(ctx, store, READY_STATE) UpdateEndHeight(ctx, store, endHeight) @@ -123,7 +124,7 @@ func (k *Keeper) GetProvenHeightFromStore(ctx sdk.Context) uint64 { return 0 } - fmt.Println("heoght buyessssssss from......", heightBytes) + fmt.Println("heightt buyessssssss from......", heightBytes) provenHeight := binary.BigEndian.Uint64(heightBytes) fmt.Println("proven height here............", provenHeight) diff --git a/relayer/publish.go b/relayer/publish.go index 6a78318..ffd3dcb 100644 --- a/relayer/publish.go +++ b/relayer/publish.go @@ -91,5 +91,12 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64) { "height_end", blocks[len(blocks)-1], "appID", string(r.rpcClient.config.AppID), ) + + // TODO : execute tx about successfull submission + + return } + + // TODO : execute tx about successfull submission + } diff --git a/relayer/submit_data.go b/relayer/submit_data.go index 7431770..55c31b8 100644 --- a/relayer/submit_data.go +++ b/relayer/submit_data.go @@ -55,7 +55,7 @@ func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks } if err == nil { - r.logger.Info("Posted block(s) to Avail DA", + r.logger.Info("Successfully posted block(s) to Avail DA", "height_start", blocks[0], "height_end", blocks[len(blocks)-1], "appID", string(r.rpcClient.config.AppID), From 9964d56dbfc33e284442a22b4a680428dc32680c Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Mon, 2 Sep 2024 14:17:09 +0530 Subject: [PATCH 25/58] execute update tx after da submission --- keeper/abci.go | 2 +- keeper/preblocker_handle.go | 2 +- keeper/submitBlobTx.go | 167 ++++++++++++++++----------------- relayer/client.go | 180 ++++++++++++++++++++++++++++++++++++ relayer/publish.go | 127 ++++++++++++++++++++++++- relayer/submit_data.go | 10 +- 6 files changed, 390 insertions(+), 98 deletions(-) create mode 100644 relayer/client.go diff --git a/keeper/abci.go b/keeper/abci.go index 1347b41..958d3c8 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -81,7 +81,7 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err // Todo: run the relayer routine // relayer doesn't have to make submitBlob Transaction, it should just start DA submission - k.relayer.PostBlocks(ctx, blocksToSumit) + k.relayer.PostBlocks(ctx, blocksToSumit, k.cdc, req.ProposerAddress) } diff --git a/keeper/preblocker_handle.go b/keeper/preblocker_handle.go index 823ee86..7636280 100644 --- a/keeper/preblocker_handle.go +++ b/keeper/preblocker_handle.go @@ -12,7 +12,7 @@ import ( func (k *Keeper) preblockerPendingBlocks(ctx sdk.Context, blockTime time.Time, proposerAddr []byte, pendingBlocks *types.PendingBlocks) error { if pendingBlocks != nil { if reflect.DeepEqual(k.proposerAddress, proposerAddr) { - k.relayer.PostBlocks(ctx, pendingBlocks.BlockHeights) + k.relayer.PostBlocks(ctx, pendingBlocks.BlockHeights, k.cdc, proposerAddr) } for _, pendingBlock := range pendingBlocks.BlockHeights { diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go index b096351..5a3cd5d 100644 --- a/keeper/submitBlobTx.go +++ b/keeper/submitBlobTx.go @@ -2,15 +2,10 @@ package keeper import ( "fmt" - "os" - cometrpc "github.com/cometbft/cometbft/rpc/client/http" - clitx "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" dacli "github.com/vitwit/avail-da-module/chainclient" "github.com/vitwit/avail-da-module/types" @@ -35,84 +30,84 @@ func (k Keeper) SubmitBlobTx2(ctx sdk.Context, msg types.MsgSubmitBlobRequest) e return nil } -func (k Keeper) SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { - // Define keyring and RPC client configuration - - homePath := "/home/vitwit/.availsdk" - keyName := "alice" - rpcAddress := "http://localhost:26657" - - // Create a keyring - kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, homePath, os.Stdin, k.cdc.(codec.Codec)) - if err != nil { - return fmt.Errorf("error creating keyring: %w", err) - } - - // List all keys in the keyring - // keys, err := kr.List() - // if err != nil { - // fmt.Println("error listing keys:", err) - // } - - info, err := kr.Key(keyName) - // log.Println("uuu....", info, err) - - valAddr, err := info.GetAddress() - - // valAddr, err := sdk.AccAddressFromBech32(addr.String()) - // fmt.Println("val addr, err..", valAddr, err, addr) - - // fmt.Println("keysss........", keys) - - // // Print out the keys - // for _, keyInfo := range keys { - // addr, err := keyInfo.GetAddress() - // fmt.Println("err..", err) - // fmt.Printf("Name: %s, Address: %s\n", keyInfo.Name, addr) - // } - - // Create an RPC client - rpcClient, err := cometrpc.NewWithTimeout(rpcAddress, "/websocket", 3) - if err != nil { - return fmt.Errorf("error creating RPC client: %w", err) - } - - // Create a new client context - clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), k.cdc, homePath, valAddr) - - // Retrieve the validator address (replace with actual logic to get the address) - // valAddr, err = sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") - // if err != nil { - // return fmt.Errorf("error parsing validator address: %w", err) - // } - - // Set the client context's from fields - clientCtx.FromName = keyName - clientCtx.FromAddress = valAddr - - // Fetch account number and sequence from the blockchain - accountRetriever := authtypes.AccountRetriever{} - account, err := accountRetriever.GetAccount(clientCtx, valAddr) - if err != nil { - return fmt.Errorf("error retrieving account: %w", err) - } - - fmt.Println("account details......", account.GetAccountNumber(), account.GetSequence()) - - // Set the correct account number and sequence - factory := NewFactory(clientCtx). - WithAccountNumber(account.GetAccountNumber()). - WithSequence(account.GetSequence()) - - // Create a transaction factory and set the validator address in the message - // factory := NewFactory(clientCtx) - msg.ValidatorAddress = valAddr.String() - // time.Sleep(10 * time.Second) - - // Generate and broadcast the transaction - if err := clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg); err != nil { - return fmt.Errorf("error broadcasting transaction: %w", err) - } - - return nil -} +// func SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest, cdc codec.Codec) error { +// // Define keyring and RPC client configuration + +// homePath := "/home/vitwit/.availsdk" +// keyName := "alice" +// rpcAddress := "http://localhost:26657" + +// // Create a keyring +// kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, homePath, os.Stdin, cdc) +// if err != nil { +// return fmt.Errorf("error creating keyring: %w", err) +// } + +// // List all keys in the keyring +// // keys, err := kr.List() +// // if err != nil { +// // fmt.Println("error listing keys:", err) +// // } + +// info, err := kr.Key(keyName) +// // log.Println("uuu....", info, err) + +// valAddr, err := info.GetAddress() + +// // valAddr, err := sdk.AccAddressFromBech32(addr.String()) +// // fmt.Println("val addr, err..", valAddr, err, addr) + +// // fmt.Println("keysss........", keys) + +// // // Print out the keys +// // for _, keyInfo := range keys { +// // addr, err := keyInfo.GetAddress() +// // fmt.Println("err..", err) +// // fmt.Printf("Name: %s, Address: %s\n", keyInfo.Name, addr) +// // } + +// // Create an RPC client +// rpcClient, err := cometrpc.NewWithTimeout(rpcAddress, "/websocket", 3) +// if err != nil { +// return fmt.Errorf("error creating RPC client: %w", err) +// } + +// // Create a new client context +// clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc, homePath, valAddr) + +// // Retrieve the validator address (replace with actual logic to get the address) +// // valAddr, err = sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") +// // if err != nil { +// // return fmt.Errorf("error parsing validator address: %w", err) +// // } + +// // Set the client context's from fields +// clientCtx.FromName = keyName +// clientCtx.FromAddress = valAddr + +// // Fetch account number and sequence from the blockchain +// accountRetriever := authtypes.AccountRetriever{} +// account, err := accountRetriever.GetAccount(clientCtx, valAddr) +// if err != nil { +// return fmt.Errorf("error retrieving account: %w", err) +// } + +// fmt.Println("account details......", account.GetAccountNumber(), account.GetSequence()) + +// // Set the correct account number and sequence +// factory := NewFactory(clientCtx). +// WithAccountNumber(account.GetAccountNumber()). +// WithSequence(account.GetSequence()) + +// // Create a transaction factory and set the validator address in the message +// // factory := NewFactory(clientCtx) +// msg.ValidatorAddress = valAddr.String() +// // time.Sleep(10 * time.Second) + +// // Generate and broadcast the transaction +// if err := clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg); err != nil { +// return fmt.Errorf("error broadcasting transaction: %w", err) +// } + +// return nil +// } diff --git a/relayer/client.go b/relayer/client.go new file mode 100644 index 0000000..0facf72 --- /dev/null +++ b/relayer/client.go @@ -0,0 +1,180 @@ +package relayer + +import ( + "fmt" + + cometrpc "github.com/cometbft/cometbft/rpc/client/http" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/std" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/go-bip39" + + // "github.com/tendermint/starport/starport/pkg/xfilepath" + + "github.com/cosmos/cosmos-sdk/types/module" +) + +const ( + defaultGasAdjustment = 1.0 + defaultGasLimit = 300000 +) + +// var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) + +func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, + cdc codec.BinaryCodec, homepath string, fromAddress sdk.AccAddress) client.Context { + encodingConfig := MakeEncodingConfig() + + broadcastMode := flags.BroadcastSync + + // homepath := "/home/vitwit/.availsdk" + + return client.Context{}. + WithCodec(cdc.(codec.Codec)). + WithChainID(chainID). + WithFromAddress(fromAddress). + WithFromName("testkey"). + WithKeyringDir(homepath). + WithBroadcastMode(broadcastMode). + WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). + WithKeyring(kr). + WithAccountRetriever(authtypes.AccountRetriever{}). + WithClient(c).WithInterfaceRegistry(encodingConfig.InterfaceRegistry). + WithSkipConfirmation(true) +} + +// NewFactory creates a new Factory. +func NewFactory(clientCtx client.Context) tx.Factory { + return tx.Factory{}. + WithChainID(clientCtx.ChainID). + WithKeybase(clientCtx.Keyring). + WithGas(defaultGasLimit). + WithGasAdjustment(defaultGasAdjustment). + WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). + WithAccountRetriever(clientCtx.AccountRetriever). + WithTxConfig(clientCtx.TxConfig) +} + +// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. +func MakeEncodingConfig(modules ...module.AppModuleBasic) EncodingConfig { + aminoCodec := codec.NewLegacyAmino() + interfaceRegistry := codectypes.NewInterfaceRegistry() + codec := codec.NewProtoCodec(interfaceRegistry) + txCfg := authTx.NewTxConfig(codec, authTx.DefaultSignModes) + + encCfg := EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Codec: codec, + TxConfig: txCfg, + Amino: aminoCodec, + } + + mb := module.NewBasicManager(modules...) + + std.RegisterLegacyAminoCodec(encCfg.Amino) + std.RegisterInterfaces(encCfg.InterfaceRegistry) + mb.RegisterLegacyAminoCodec(encCfg.Amino) + mb.RegisterInterfaces(encCfg.InterfaceRegistry) + + return encCfg +} + +// func MakeTestEncodingConfig(modules ...module.AppModuleBasic) TestEncodingConfig { +// aminoCodec := codec.NewLegacyAmino() +// interfaceRegistry := testutil.CodecOptions{}.NewInterfaceRegistry() +// codec := codec.NewProtoCodec(interfaceRegistry) + +// encCfg := TestEncodingConfig{ +// InterfaceRegistry: interfaceRegistry, +// Codec: codec, +// TxConfig: tx.NewTxConfig(codec, tx.DefaultSignModes), +// Amino: aminoCodec, +// } + +// mb := module.NewBasicManager(modules...) + +// std.RegisterLegacyAminoCodec(encCfg.Amino) +// std.RegisterInterfaces(encCfg.InterfaceRegistry) +// mb.RegisterLegacyAminoCodec(encCfg.Amino) +// mb.RegisterInterfaces(encCfg.InterfaceRegistry) + +// return encCfg +// } + +// EncodingConfig specifies the concrete encoding types to use for a given app. +// This is provided for compatibility between protobuf and amino implementations. +type EncodingConfig struct { + InterfaceRegistry codectypes.InterfaceRegistry + Codec codec.Codec + TxConfig client.TxConfig + Amino *codec.LegacyAmino +} + +// ImportMnemonic is to import existing account mnemonic in keyring +func ImportMnemonic(keyName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { + info, err := AccountCreate(keyName, mnemonic, hdPath, c) // return account also + // fmt.Println("here the accc details.......", keyName, mnemonic, hdPath) + if err != nil { + return nil, err + } + + return info, nil +} + +// AccountCreate creates an account by name and mnemonic (optional) in the keyring. +func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { + if mnemonic == "" { + entropySeed, err := bip39.NewEntropy(256) + if err != nil { + return nil, err + } + mnemonic, err = bip39.NewMnemonic(entropySeed) + fmt.Println("mnemoniccccc here.....", mnemonic) + if err != nil { + return nil, err + } + } + + algos, _ := c.Keyring.SupportedAlgorithms() + algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algos) + if err != nil { + return nil, err + } + + path := hd.CreateHDPath(118, 0, 0).String() + // fmt.Println("pathhh......", path) + + // record, str, err := c.Keyring.NewMnemonic("test_key1", keyring.English, path, keyring.DefaultBIP39Passphrase, hd.Secp256k1) + // fmt.Println("recorddddd.......", err, str, record) + + // k, _, err = kb.NewMnemonic("test", English, types.FullFundraiserPath, DefaultBIP39Passphrase, hd.Secp256k1) + info, err := c.Keyring.NewAccount(accountName, mnemonic, keyring.DefaultBIP39Passphrase, path, algo) + fmt.Println("after creationnnn.........", info, err) + if err != nil { + return nil, err + } + // pk, err := info.GetPubKey() + // if err != nil { + // return nil, err + // } + + // addr := sdk.AccAddress(pk.Address()) + // fmt.Println("address hereee...", addr) + + // aa, err := info.GetAddress() + // fmt.Println("here aa and err.......", aa, err) + + // account := c.ToAccount(info) + // account.Mnemonic = mnemonic + return info, nil + // return nil +} diff --git a/relayer/publish.go b/relayer/publish.go index ffd3dcb..4217cdc 100644 --- a/relayer/publish.go +++ b/relayer/publish.go @@ -1,8 +1,17 @@ package relayer import ( + "fmt" + "os" + + cometrpc "github.com/cometbft/cometbft/rpc/client/http" + clitx "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/vitwit/avail-da-module/types" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) // PostNextBlocks is called by the current proposing validator during PrepareProposal. @@ -48,13 +57,13 @@ func (r *Relayer) ProposePostNextBlocks(ctx sdk.Context, provenHeight int64) []i } // PostBlocks is call in the preblocker, the proposer will publish at this point with their block accepted -func (r *Relayer) PostBlocks(ctx sdk.Context, blocks []int64) { - go r.postBlocks(ctx, blocks) +func (r *Relayer) PostBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCodec, proposer []byte) { + go r.postBlocks(ctx, blocks, cdc, proposer) } // postBlocks will publish rollchain blocks to avail // start height is inclusive, end height is exclusive -func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64) { +func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCodec, proposer []byte) { // process blocks instead of random data if len(blocks) == 0 { return @@ -84,7 +93,7 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64) { bb = append(bb, blockBz...) } - err := r.SubmitDataToClient(r.rpcClient.config.Seed, r.rpcClient.config.AppID, bb, blocks, r.rpcClient.config.LightClientURL) + blockInfo, err := r.SubmitDataToClient(r.rpcClient.config.Seed, r.rpcClient.config.AppID, bb, blocks, r.rpcClient.config.LightClientURL) if err != nil { r.logger.Error("Error while submitting block(s) to Avail DA", "height_start", blocks[0], @@ -92,11 +101,119 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64) { "appID", string(r.rpcClient.config.AppID), ) - // TODO : execute tx about successfull submission + // TODO : execute tx about failure submission + err = ExecuteTX(ctx, types.MsgUpdateBlobStatusRequest{ + ValidatorAddress: sdk.AccAddress.String(proposer), + BlocksRange: &types.Range{ + From: uint64(blocks[0]), + To: uint64(blocks[len(blocks)-1]), + }, + // AvailHeight: uint64(blockInfo.BlockNumber), + IsSuccess: false, + }, cdc) + if err != nil { + fmt.Println("error while submitting tx...", err) + } return } + fmt.Println("proposer addressss........", sdk.AccAddress.String(proposer), + uint64(blocks[0]), uint64(blocks[len(blocks)-1]), uint64(blockInfo.BlockNumber)) + // TODO : execute tx about successfull submission + err = ExecuteTX(ctx, types.MsgUpdateBlobStatusRequest{ + ValidatorAddress: sdk.AccAddress.String(proposer), + BlocksRange: &types.Range{ + From: uint64(blocks[0]), + To: uint64(blocks[len(blocks)-1]), + }, + AvailHeight: uint64(blockInfo.BlockNumber), + IsSuccess: true, + }, cdc) + if err != nil { + fmt.Println("error while submitting tx...", err) + } +} + +func ExecuteTX(ctx sdk.Context, msg types.MsgUpdateBlobStatusRequest, cdc codec.BinaryCodec) error { + // Define keyring and RPC client configuration + + homePath := "/home/vitwit/.availsdk" + keyName := "alice" + rpcAddress := "http://localhost:26657" + + // Create a keyring + kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, homePath, os.Stdin, cdc.(codec.Codec)) + if err != nil { + return fmt.Errorf("error creating keyring: %w", err) + } + + // List all keys in the keyring + // keys, err := kr.List() + // if err != nil { + // fmt.Println("error listing keys:", err) + // } + + info, err := kr.Key(keyName) + // log.Println("uuu....", info, err) + + valAddr, err := info.GetAddress() + + // valAddr, err := sdk.AccAddressFromBech32(addr.String()) + // fmt.Println("val addr, err..", valAddr, err, addr) + + // fmt.Println("keysss........", keys) + + // // Print out the keys + // for _, keyInfo := range keys { + // addr, err := keyInfo.GetAddress() + // fmt.Println("err..", err) + // fmt.Printf("Name: %s, Address: %s\n", keyInfo.Name, addr) + // } + + // Create an RPC client + rpcClient, err := cometrpc.NewWithTimeout(rpcAddress, "/websocket", 3) + if err != nil { + return fmt.Errorf("error creating RPC client: %w", err) + } + + // Create a new client context + clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc, homePath, valAddr) + + // Retrieve the validator address (replace with actual logic to get the address) + // valAddr, err = sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") + // if err != nil { + // return fmt.Errorf("error parsing validator address: %w", err) + // } + + // Set the client context's from fields + clientCtx.FromName = keyName + clientCtx.FromAddress = valAddr + + // Fetch account number and sequence from the blockchain + accountRetriever := authtypes.AccountRetriever{} + account, err := accountRetriever.GetAccount(clientCtx, valAddr) + if err != nil { + return fmt.Errorf("error retrieving account: %w", err) + } + + fmt.Println("account details......", account.GetAccountNumber(), account.GetSequence()) + + // Set the correct account number and sequence + factory := NewFactory(clientCtx). + WithAccountNumber(account.GetAccountNumber()). + WithSequence(account.GetSequence()) + + // Create a transaction factory and set the validator address in the message + // factory := NewFactory(clientCtx) + msg.ValidatorAddress = valAddr.String() + // time.Sleep(10 * time.Second) + + // Generate and broadcast the transaction + if err := clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg); err != nil { + return fmt.Errorf("error broadcasting transaction: %w", err) + } + return nil } diff --git a/relayer/submit_data.go b/relayer/submit_data.go index 55c31b8..12d3e90 100644 --- a/relayer/submit_data.go +++ b/relayer/submit_data.go @@ -16,9 +16,10 @@ import ( "github.com/centrifuge/go-substrate-rpc-client/v4/types" ) -func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks []int64, lightClientUrl string) error { +func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks []int64, lightClientUrl string) (BlockInfo, error) { + var blockInfo BlockInfo if r.submittedBlocksCache[blocks[0]] { - return nil + return blockInfo, nil } r.submittedBlocksCache[blocks[0]] = true @@ -38,11 +39,10 @@ func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks responseBody, err := handler.Post(url, jsonData) if err != nil { fmt.Printf("Error: %v\n", err) - return err + return blockInfo, err } // Create an instance of the struct - var blockInfo BlockInfo // Unmarshal the JSON data into the struct err = json.Unmarshal(responseBody, &blockInfo) @@ -65,7 +65,7 @@ func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks ) } - return nil + return blockInfo, nil } func (r *Relayer) GetSubmittedData(lightClientUrl string, blockNumber int) { From 6262360cb5750ffe85a698c5e787b1a936531fdf Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Mon, 2 Sep 2024 15:41:08 +0530 Subject: [PATCH 26/58] fix --- keeper/abci.go | 7 +++-- keeper/preblocker_handle.go | 24 +++++++-------- keeper/prepare_handle.go | 24 ++++++++------- keeper/process_handle.go | 61 ++++++++++++++++++------------------- relayer/publish.go | 31 ++++++++++--------- relayer/submit_data.go | 1 + 6 files changed, 77 insertions(+), 71 deletions(-) diff --git a/keeper/abci.go b/keeper/abci.go index 958d3c8..82da269 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -43,14 +43,16 @@ func (h *ProofOfBlobProposalHandler) ProcessProposal(ctx sdk.Context, req *abci. } func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { - // fmt.Println("coming hereee.........", req) + fmt.Println("coming hereee.........", ctx.BlockHeight()) currentBlockHeight := ctx.BlockHeight() if !k.IsValidBlockToPostTODA(uint64(currentBlockHeight)) { return nil } - fmt.Println("block heighttt.........", ctx.BlockHeight()) + // fmt.Printf("Ctx.........%+v\n", ctx) + + fmt.Println("block heighttt.........", ctx.BlockHeight(), ctx.ExecMode(), ctx.IsCheckTx(), ctx.IsReCheckTx()) fromHeight := k.GetProvenHeightFromStore(ctx) //Todo: change this get from ProvenHeight from store fmt.Println("from height..", fromHeight) @@ -61,6 +63,7 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err err := k.SetBlobStatusPending(sdkCtx, fromHeight, endHeight) if err != nil { fmt.Println("error while setting blob status...", err) + return nil // TODO: check consensus failure issue } var blocksToSumit []int64 diff --git a/keeper/preblocker_handle.go b/keeper/preblocker_handle.go index 7636280..e5891a8 100644 --- a/keeper/preblocker_handle.go +++ b/keeper/preblocker_handle.go @@ -1,8 +1,6 @@ package keeper import ( - "fmt" - "reflect" "time" sdk "github.com/cosmos/cosmos-sdk/types" @@ -10,17 +8,17 @@ import ( ) func (k *Keeper) preblockerPendingBlocks(ctx sdk.Context, blockTime time.Time, proposerAddr []byte, pendingBlocks *types.PendingBlocks) error { - if pendingBlocks != nil { - if reflect.DeepEqual(k.proposerAddress, proposerAddr) { - k.relayer.PostBlocks(ctx, pendingBlocks.BlockHeights, k.cdc, proposerAddr) - } - - for _, pendingBlock := range pendingBlocks.BlockHeights { - if err := k.AddUpdatePendingBlock(ctx, pendingBlock, blockTime); err != nil { - return fmt.Errorf("preblocker pending blocks, %v", err) - } - } - } + // if pendingBlocks != nil { + // if reflect.DeepEqual(k.proposerAddress, proposerAddr) { + // k.relayer.PostBlocks(ctx, pendingBlocks.BlockHeights, k.cdc, proposerAddr) + // } + + // for _, pendingBlock := range pendingBlocks.BlockHeights { + // if err := k.AddUpdatePendingBlock(ctx, pendingBlock, blockTime); err != nil { + // return fmt.Errorf("preblocker pending blocks, %v", err) + // } + // } + // } return nil } diff --git a/keeper/prepare_handle.go b/keeper/prepare_handle.go index 990a798..7a1ab2d 100644 --- a/keeper/prepare_handle.go +++ b/keeper/prepare_handle.go @@ -11,9 +11,10 @@ import ( const DelayAfterUpgrade = int64(10) func (k *Keeper) prepareInjectData(ctx sdk.Context, currentBlockTime time.Time, latestProvenHeight int64) types.InjectedData { - return types.InjectedData{ - PendingBlocks: k.preparePostBlocks(ctx, currentBlockTime), - } + // return types.InjectedData{ + // PendingBlocks: k.preparePostBlocks(ctx, currentBlockTime), + // } + return types.InjectedData{} } func (k *Keeper) addAvailblobDataToTxs(injectDataBz []byte, maxTxBytes int64, txs [][]byte) [][]byte { @@ -36,11 +37,11 @@ func (k *Keeper) addAvailblobDataToTxs(injectDataBz []byte, maxTxBytes int64, tx } func (k *Keeper) preparePostBlocks(ctx sdk.Context, currentBlockTime time.Time) types.PendingBlocks { - provenHeight, err := k.GetProvenHeight(ctx) - if err != nil { - return types.PendingBlocks{} - } - newBlocks := k.relayer.ProposePostNextBlocks(ctx, provenHeight) + // provenHeight, err := k.GetProvenHeight(ctx) + // if err != nil { + // return types.PendingBlocks{} + // } + // newBlocks := k.relayer.ProposePostNextBlocks(ctx, provenHeight) // If there are no new blocks to propose, check for expired blocks // Additionally, if the block interval is 1, we need to also be able to re-publish an expired block @@ -58,9 +59,10 @@ func (k *Keeper) preparePostBlocks(ctx sdk.Context, currentBlockTime time.Time) // } // } - return types.PendingBlocks{ - BlockHeights: newBlocks, - } + // return types.PendingBlocks{ + // BlockHeights: newBlocks, + // } + return types.PendingBlocks{} } // shouldGetExpiredBlocks checks if this chain has recently upgraded. diff --git a/keeper/process_handle.go b/keeper/process_handle.go index f047188..8f23397 100644 --- a/keeper/process_handle.go +++ b/keeper/process_handle.go @@ -1,7 +1,6 @@ package keeper import ( - "fmt" "time" sdk "github.com/cosmos/cosmos-sdk/types" @@ -9,36 +8,36 @@ import ( ) func (k Keeper) processPendingBlocks(ctx sdk.Context, currentBlockTime time.Time, pendingBlocks *types.PendingBlocks) error { - if pendingBlocks != nil { - height := ctx.BlockHeight() - numBlocks := len(pendingBlocks.BlockHeights) - if numBlocks > 2 && numBlocks > k.publishToAvailBlockInterval { - return fmt.Errorf("process pending blocks, included pending blocks (%d) exceeds limit (%d)", numBlocks, k.publishToAvailBlockInterval) - } - for _, pendingBlock := range pendingBlocks.BlockHeights { - if pendingBlock <= 0 { - return fmt.Errorf("process pending blocks, invalid block: %d", pendingBlock) - } - if pendingBlock >= height { - return fmt.Errorf("process pending blocks, start (%d) cannot be >= this block height (%d)", pendingBlock, height) - } - // Check if already pending, if so, is it expired? - if k.IsBlockPending(ctx, pendingBlock) && !k.IsBlockExpired(ctx, currentBlockTime, pendingBlock) { - return fmt.Errorf("process pending blocks, block height (%d) is pending, but not expired", pendingBlock) - } - } - // Ensure publish boundries includes new blocks, once they are on-chain, they will be tracked appropriately - provenHeight, err := k.GetProvenHeight(ctx) - if err != nil { - return fmt.Errorf("process pending blocks, getting proven height, %v", err) - } - newBlocks := k.relayer.ProposePostNextBlocks(ctx, provenHeight) - for i, newBlock := range newBlocks { - if newBlock != pendingBlocks.BlockHeights[i] { - return fmt.Errorf("process pending blocks, block (%d) must be included", newBlock) - } - } - } + // if pendingBlocks != nil { + // height := ctx.BlockHeight() + // numBlocks := len(pendingBlocks.BlockHeights) + // if numBlocks > 2 && numBlocks > k.publishToAvailBlockInterval { + // return fmt.Errorf("process pending blocks, included pending blocks (%d) exceeds limit (%d)", numBlocks, k.publishToAvailBlockInterval) + // } + // for _, pendingBlock := range pendingBlocks.BlockHeights { + // if pendingBlock <= 0 { + // return fmt.Errorf("process pending blocks, invalid block: %d", pendingBlock) + // } + // if pendingBlock >= height { + // return fmt.Errorf("process pending blocks, start (%d) cannot be >= this block height (%d)", pendingBlock, height) + // } + // // Check if already pending, if so, is it expired? + // if k.IsBlockPending(ctx, pendingBlock) && !k.IsBlockExpired(ctx, currentBlockTime, pendingBlock) { + // return fmt.Errorf("process pending blocks, block height (%d) is pending, but not expired", pendingBlock) + // } + // } + // // Ensure publish boundries includes new blocks, once they are on-chain, they will be tracked appropriately + // provenHeight, err := k.GetProvenHeight(ctx) + // if err != nil { + // return fmt.Errorf("process pending blocks, getting proven height, %v", err) + // } + // newBlocks := k.relayer.ProposePostNextBlocks(ctx, provenHeight) + // for i, newBlock := range newBlocks { + // if newBlock != pendingBlocks.BlockHeights[i] { + // return fmt.Errorf("process pending blocks, block (%d) must be included", newBlock) + // } + // } + // } return nil } diff --git a/relayer/publish.go b/relayer/publish.go index 4217cdc..2d4cd58 100644 --- a/relayer/publish.go +++ b/relayer/publish.go @@ -118,22 +118,25 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo return } - fmt.Println("proposer addressss........", sdk.AccAddress.String(proposer), - uint64(blocks[0]), uint64(blocks[len(blocks)-1]), uint64(blockInfo.BlockNumber)) + if blockInfo.BlockNumber != 0 { + fmt.Println("proposer addressss........", sdk.AccAddress.String(proposer), + uint64(blocks[0]), uint64(blocks[len(blocks)-1]), uint64(blockInfo.BlockNumber)) - // TODO : execute tx about successfull submission - err = ExecuteTX(ctx, types.MsgUpdateBlobStatusRequest{ - ValidatorAddress: sdk.AccAddress.String(proposer), - BlocksRange: &types.Range{ - From: uint64(blocks[0]), - To: uint64(blocks[len(blocks)-1]), - }, - AvailHeight: uint64(blockInfo.BlockNumber), - IsSuccess: true, - }, cdc) - if err != nil { - fmt.Println("error while submitting tx...", err) + // TODO : execute tx about successfull submission + err = ExecuteTX(ctx, types.MsgUpdateBlobStatusRequest{ + ValidatorAddress: sdk.AccAddress.String(proposer), + BlocksRange: &types.Range{ + From: uint64(blocks[0]), + To: uint64(blocks[len(blocks)-1]), + }, + AvailHeight: uint64(blockInfo.BlockNumber), + IsSuccess: true, + }, cdc) + if err != nil { + fmt.Println("error while submitting tx...", err) + } } + } func ExecuteTX(ctx sdk.Context, msg types.MsgUpdateBlobStatusRequest, cdc codec.BinaryCodec) error { diff --git a/relayer/submit_data.go b/relayer/submit_data.go index 12d3e90..11f9986 100644 --- a/relayer/submit_data.go +++ b/relayer/submit_data.go @@ -17,6 +17,7 @@ import ( ) func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks []int64, lightClientUrl string) (BlockInfo, error) { + fmt.Println("calling twiceeeee.........", blocks) var blockInfo BlockInfo if r.submittedBlocksCache[blocks[0]] { return blockInfo, nil From 41b3697f915bc76a54f34812526dd0f0e559e0c4 Mon Sep 17 00:00:00 2001 From: saiteja Date: Mon, 2 Sep 2024 17:26:26 +0530 Subject: [PATCH 27/58] query and tx --- client/cli/query.go | 28 ++++ keeper/abci.go | 1 + keeper/keeper.go | 54 ++++++- keeper/store.go | 27 ++++ module/module.go | 4 + proto/sdk/avail/v1beta1/query.proto | 4 +- types/query.pb.go | 218 ++++++++++++++-------------- types/query.pb.gw.go | 18 --- 8 files changed, 223 insertions(+), 131 deletions(-) diff --git a/client/cli/query.go b/client/cli/query.go index aa5160c..0cd075b 100644 --- a/client/cli/query.go +++ b/client/cli/query.go @@ -2,8 +2,10 @@ package cli import ( "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" availblob "github.com/vitwit/avail-da-module" + "github.com/vitwit/avail-da-module/types" ) func GetQueryCmd() *cobra.Command { @@ -13,5 +15,31 @@ func GetQueryCmd() *cobra.Command { RunE: client.ValidateCmd, } + cmd.AddCommand(GetLatestBlobStatusInfo()) + + return cmd +} + +func GetLatestBlobStatusInfo() *cobra.Command { + cmd := &cobra.Command{ + Use: "get-da-status", + Short: "Show what range of blocks are being submitted and thier status", + Long: `Show what range of blocks are being submitted and thier status, + `, + Args: cobra.ExactArgs(0), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + req := &types.QuerySubmitBlobStatusRequest{} + res, _ := queryClient.SubmitBlobStatus(cmd.Context(), req) + + return clientCtx.PrintProto(res) + }, + } + flags.AddQueryFlagsToCmd(cmd) return cmd } diff --git a/keeper/abci.go b/keeper/abci.go index 958d3c8..4ecb8a8 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -61,6 +61,7 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err err := k.SetBlobStatusPending(sdkCtx, fromHeight, endHeight) if err != nil { fmt.Println("error while setting blob status...", err) + return nil } var blocksToSumit []int64 diff --git a/keeper/keeper.go b/keeper/keeper.go index 63b9944..2f192d6 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -120,7 +120,7 @@ func (k *Keeper) SetBlobStatusSuccess(ctx sdk.Context, provenHeight, endHeight u func (k *Keeper) GetProvenHeightFromStore(ctx sdk.Context) uint64 { store := ctx.KVStore(k.storeKey) heightBytes := store.Get(availblob1.ProvenHeightKey) - if heightBytes == nil || len(heightBytes) == 8 { + if heightBytes == nil || len(heightBytes) == 0 { return 0 } @@ -131,6 +131,22 @@ func (k *Keeper) GetProvenHeightFromStore(ctx sdk.Context) uint64 { return provenHeight } +func (k *Keeper) GetEndHeightFromStore(ctx sdk.Context) uint64 { + store := ctx.KVStore(k.storeKey) + heightBytes := store.Get(availblob1.NextHeightKey) + + fmt.Println("heightBytes getEnd........", heightBytes) + if heightBytes == nil || len(heightBytes) == 0 { + return 0 + } + + fmt.Println("heightt buyessssssss from......", heightBytes) + + nextHeight := binary.BigEndian.Uint64(heightBytes) + fmt.Println("proven height here............", nextHeight) + return nextHeight +} + // Todo: remove this method later func (k *Keeper) SubmitBlob(ctx sdk.Context, req *types.MsgSubmitBlobRequest) (*types.MsgSubmitBlobResponse, error) { @@ -139,6 +155,28 @@ func (k *Keeper) SubmitBlob(ctx sdk.Context, req *types.MsgSubmitBlobRequest) (* func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatusRequest) (*types.MsgUpdateBlobStatusResponse, error) { //Todo: status should be changed to Voting or Ready, depending on the request + store := ctx.KVStore(k.storeKey) + provenHeight := k.GetProvenHeightFromStore(ctx) + endHeight := k.GetEndHeightFromStore(ctx) + status := GetStatusFromStore(store) + + if req.BlocksRange.From != provenHeight+1 || req.BlocksRange.To != endHeight { + return nil, errors.New("invalid blocks range") + } + + if status != PENDING_STATE { + return nil, errors.New("can update the status if it is not pending") + } + + newStatus := READY_STATE + if !req.IsSuccess { + newStatus = PENDING_STATE + } else { + UpdateProvenHeight(ctx, store, endHeight) + } + + UpdateBlobStatus(ctx, store, newStatus) + return &types.MsgUpdateBlobStatusResponse{}, nil } @@ -160,5 +198,17 @@ func (k *Keeper) CheckHeight(endHeight uint64) error { func (k *Keeper) SubmitBlobStatus(ctx sdk.Context, _ *types.QuerySubmitBlobStatusRequest) (*types.QuerySubmitBlobStatusResponse, error) { // Todo: implement query - return nil, nil + store := ctx.KVStore(k.storeKey) + provenHeight := k.GetProvenHeightFromStore(ctx) + endHeight := k.GetEndHeightFromStore(ctx) + status := GetStatusFromStore(store) + statusString := ParseStatus(status) + startHeight := provenHeight + 1 + if provenHeight == 0 { + startHeight = 0 + } + return &types.QuerySubmitBlobStatusResponse{ + Range: &types.Range{From: startHeight, To: endHeight}, + Status: statusString, + }, nil } diff --git a/keeper/store.go b/keeper/store.go index e034687..604e22c 100644 --- a/keeper/store.go +++ b/keeper/store.go @@ -17,6 +17,21 @@ const ( FAILURE_STATE uint32 = 3 ) +func ParseStatus(status uint32) string { + switch status { + case READY_STATE: + return "SUCCESS" + case PENDING_STATE: + return "PENDING" + case IN_VOTING_STATE: + return "IN_VOTING" + case FAILURE_STATE: + return "FAILUTE" + default: + return "UNKNOWN" + } +} + func IsAlreadyExist(ctx sdk.Context, store storetypes2.KVStore, blocksRange types.Range) bool { pendingBlobStoreKey := availblob1.PendingBlobsStoreKey(blocksRange) blobStatus := store.Get(pendingBlobStoreKey) @@ -39,6 +54,18 @@ func IsStateReady(store storetypes2.KVStore) bool { return status == READY_STATE } +func GetStatusFromStore(store storetypes2.KVStore) uint32 { + statusBytes := store.Get(availblob1.BlobStatusKey) + + if statusBytes == nil || len(statusBytes) == 0 { + return READY_STATE + } + + status := binary.BigEndian.Uint32(statusBytes) + + return status +} + func UpdateBlobStatus(ctx sdk.Context, store storetypes2.KVStore, status uint32) error { statusBytes := make([]byte, 4) diff --git a/module/module.go b/module/module.go index b1c5d93..ad42452 100644 --- a/module/module.go +++ b/module/module.go @@ -66,6 +66,10 @@ func (am AppModule) GetTxCmd() *cobra.Command { return cli.NewTxCmd(am.keeper) } +func (AppModule) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + // RegisterInterfaces registers interfaces and implementations of the rollchain module. func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) diff --git a/proto/sdk/avail/v1beta1/query.proto b/proto/sdk/avail/v1beta1/query.proto index f5f850a..ee88aec 100644 --- a/proto/sdk/avail/v1beta1/query.proto +++ b/proto/sdk/avail/v1beta1/query.proto @@ -11,12 +11,12 @@ option go_package = "github.com/vitwit/avail-da-module/types"; // query request message QuerySubmitBlobStatusRequest { - Range range = 1; } // query response message QuerySubmitBlobStatusResponse { - string status = 1; + Range range = 1; + string status = 2; } // Query defines the gRPC querier service. diff --git a/types/query.pb.go b/types/query.pb.go index a66c02c..94c269a 100644 --- a/types/query.pb.go +++ b/types/query.pb.go @@ -35,7 +35,6 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // query request type QuerySubmitBlobStatusRequest struct { - Range *Range `protobuf:"bytes,1,opt,name=range,proto3" json:"range,omitempty"` } func (m *QuerySubmitBlobStatusRequest) Reset() { *m = QuerySubmitBlobStatusRequest{} } @@ -71,16 +70,10 @@ func (m *QuerySubmitBlobStatusRequest) XXX_DiscardUnknown() { var xxx_messageInfo_QuerySubmitBlobStatusRequest proto.InternalMessageInfo -func (m *QuerySubmitBlobStatusRequest) GetRange() *Range { - if m != nil { - return m.Range - } - return nil -} - // query response type QuerySubmitBlobStatusResponse struct { - Status string `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"` + Range *Range `protobuf:"bytes,1,opt,name=range,proto3" json:"range,omitempty"` + Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"` } func (m *QuerySubmitBlobStatusResponse) Reset() { *m = QuerySubmitBlobStatusResponse{} } @@ -116,6 +109,13 @@ func (m *QuerySubmitBlobStatusResponse) XXX_DiscardUnknown() { var xxx_messageInfo_QuerySubmitBlobStatusResponse proto.InternalMessageInfo +func (m *QuerySubmitBlobStatusResponse) GetRange() *Range { + if m != nil { + return m.Range + } + return nil +} + func (m *QuerySubmitBlobStatusResponse) GetStatus() string { if m != nil { return m.Status @@ -616,54 +616,54 @@ func init() { func init() { proto.RegisterFile("sdk/avail/v1beta1/query.proto", fileDescriptor_30ff5d91ce731c68) } var fileDescriptor_30ff5d91ce731c68 = []byte{ - // 740 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0x41, 0x4f, 0xd4, 0x40, - 0x14, 0xc7, 0xb7, 0x20, 0xa8, 0xc3, 0x62, 0x60, 0x34, 0xb8, 0x56, 0xd8, 0x85, 0x12, 0x14, 0x44, - 0x5a, 0xc1, 0x83, 0x57, 0xd9, 0x68, 0xf0, 0xa2, 0xd1, 0x62, 0x34, 0x31, 0x31, 0x9b, 0x29, 0x1d, - 0xbb, 0xcd, 0x76, 0x3b, 0xa5, 0x33, 0x5d, 0xe1, 0xea, 0xd1, 0x13, 0x09, 0x07, 0xe3, 0xd5, 0xcf, - 0xe0, 0x87, 0xe0, 0x48, 0xe2, 0xc5, 0x93, 0x1a, 0xf0, 0x83, 0x98, 0x4e, 0xa7, 0xa5, 0xdd, 0x9d, - 0x6e, 0xd6, 0x5b, 0xa7, 0xff, 0xf7, 0xfe, 0xf3, 0x7b, 0x33, 0xf3, 0x1e, 0x58, 0xa0, 0x76, 0xc7, - 0x40, 0x3d, 0xe4, 0x7a, 0x46, 0x6f, 0xd3, 0xc2, 0x0c, 0x6d, 0x1a, 0xfb, 0x11, 0x0e, 0x0f, 0xf5, - 0x20, 0x24, 0x8c, 0xc0, 0x59, 0x6a, 0x77, 0x74, 0x2e, 0xeb, 0x42, 0x56, 0x6f, 0x38, 0xc4, 0x21, - 0x5c, 0x35, 0xe2, 0xaf, 0x24, 0x50, 0x9d, 0x77, 0x08, 0x71, 0x3c, 0x6c, 0xa0, 0xc0, 0x35, 0x90, - 0xef, 0x13, 0x86, 0x98, 0x4b, 0x7c, 0x2a, 0xd4, 0xa5, 0xc1, 0x5d, 0x7a, 0xc8, 0x73, 0x6d, 0xc4, - 0x48, 0x28, 0x42, 0x1a, 0xc2, 0x80, 0xaf, 0xac, 0xe8, 0x83, 0xc1, 0xdc, 0x2e, 0xa6, 0x0c, 0x75, - 0x03, 0x11, 0xa0, 0x0e, 0x7a, 0xb0, 0x83, 0x44, 0xd3, 0x5e, 0x80, 0xf9, 0x57, 0x31, 0xf5, 0x6e, - 0x64, 0x75, 0x5d, 0xd6, 0xf4, 0x88, 0xb5, 0xcb, 0x10, 0x8b, 0xa8, 0x89, 0xf7, 0x23, 0x4c, 0x19, - 0xd4, 0xc1, 0x44, 0x88, 0x7c, 0x07, 0xd7, 0x94, 0x45, 0x65, 0x75, 0x6a, 0xab, 0xa6, 0x0f, 0x94, - 0xa5, 0x9b, 0xb1, 0x6e, 0x26, 0x61, 0xda, 0x23, 0xb0, 0x50, 0xe2, 0x47, 0x03, 0xe2, 0x53, 0x0c, - 0xe7, 0xc0, 0x24, 0xe5, 0x7f, 0xb8, 0xe3, 0x55, 0x53, 0xac, 0xb4, 0x1a, 0x98, 0xe3, 0x89, 0x6f, - 0xd2, 0xea, 0x52, 0x04, 0xed, 0x3d, 0xb8, 0x39, 0xa0, 0x08, 0xb3, 0x26, 0x00, 0xd9, 0x69, 0xc4, - 0x86, 0xe3, 0xab, 0x53, 0x5b, 0xf3, 0x12, 0xc4, 0x2c, 0xb5, 0x79, 0xe9, 0xe4, 0x57, 0xa3, 0x62, - 0xe6, 0xb2, 0xb4, 0x1d, 0x50, 0xe3, 0xf6, 0xdb, 0x71, 0xc6, 0xb6, 0x6d, 0x87, 0x98, 0x66, 0xd5, - 0xaf, 0x83, 0xd9, 0x2c, 0xb2, 0x85, 0x12, 0x4d, 0x70, 0xcf, 0x64, 0x82, 0xc8, 0xd1, 0x1e, 0x83, - 0x5b, 0x12, 0x23, 0x41, 0xba, 0x0c, 0xa6, 0x39, 0x52, 0x9f, 0x4b, 0x15, 0xe5, 0x82, 0x35, 0x55, - 0xa0, 0xbc, 0x0c, 0x49, 0x0f, 0xfb, 0xcf, 0xb0, 0xeb, 0xb4, 0x59, 0x7a, 0x0a, 0xa9, 0x7b, 0x51, - 0xbb, 0x70, 0x0f, 0xf8, 0xff, 0x56, 0x9b, 0x0b, 0xdc, 0x7d, 0xdc, 0xac, 0x06, 0xb9, 0x60, 0x8d, - 0x82, 0xeb, 0x4d, 0x8f, 0xec, 0x75, 0xde, 0xba, 0xac, 0xfd, 0xf4, 0x20, 0x70, 0x43, 0xfe, 0xd0, - 0xe2, 0x0b, 0x29, 0x24, 0x89, 0x15, 0x7c, 0x02, 0x00, 0xce, 0xa2, 0x6a, 0x63, 0xfc, 0xfa, 0x55, - 0x3d, 0x79, 0x6b, 0x7a, 0xfa, 0xd6, 0xf4, 0xd7, 0xe9, 0x5b, 0x6b, 0x5e, 0x89, 0x4f, 0xf6, 0xe8, - 0x77, 0x43, 0x31, 0x73, 0x79, 0xda, 0xed, 0x14, 0x1b, 0xfb, 0xb6, 0xeb, 0x3b, 0x1c, 0x20, 0xbb, - 0xd9, 0x0e, 0x50, 0x65, 0xa2, 0x28, 0xea, 0x39, 0xb8, 0x16, 0x24, 0x42, 0xcb, 0xe2, 0x8a, 0xb8, - 0xe0, 0x3b, 0x92, 0x0b, 0x96, 0x14, 0x66, 0x4e, 0x07, 0x79, 0xdb, 0x8c, 0x84, 0x47, 0x60, 0xbb, - 0x48, 0xf2, 0x5d, 0x11, 0x28, 0x7d, 0xaa, 0x40, 0xd9, 0x01, 0xd5, 0xbd, 0x28, 0x0c, 0xb1, 0xcf, - 0x5a, 0x71, 0x73, 0x89, 0x66, 0x18, 0xed, 0x34, 0xa6, 0x44, 0x66, 0xac, 0xc5, 0x35, 0xe1, 0x64, - 0x87, 0xb4, 0xa6, 0xb1, 0xff, 0xab, 0x09, 0xe7, 0xf9, 0xb6, 0xbe, 0x5e, 0x06, 0x13, 0x1c, 0x1b, - 0x7e, 0x53, 0xc0, 0x4c, 0x7f, 0xcf, 0x41, 0x43, 0xe2, 0x3a, 0xac, 0xdb, 0xd5, 0x07, 0xa3, 0x27, - 0x24, 0x27, 0xa3, 0xad, 0x7f, 0xfa, 0xf1, 0xf7, 0x78, 0x6c, 0x05, 0x2e, 0x27, 0x03, 0xc6, 0xf2, - 0x88, 0x95, 0x0d, 0x19, 0xda, 0xcf, 0xf3, 0x59, 0x01, 0xe0, 0xa2, 0x8b, 0xe1, 0x5a, 0xd9, 0x6e, - 0x03, 0x33, 0x40, 0xbd, 0x37, 0x4a, 0xa8, 0x40, 0x5a, 0xe1, 0x48, 0x0d, 0xb8, 0x20, 0x41, 0xba, - 0xe8, 0x7b, 0x78, 0xac, 0x80, 0x6a, 0xbe, 0x55, 0xe1, 0x7a, 0xd9, 0x1e, 0x92, 0xc9, 0xa0, 0xde, - 0x1f, 0x2d, 0x58, 0x20, 0xad, 0x72, 0x24, 0x0d, 0x2e, 0x4a, 0x90, 0x0a, 0x63, 0x81, 0x53, 0xe5, - 0x5b, 0xbc, 0x9c, 0x4a, 0x32, 0x24, 0xca, 0xa9, 0x64, 0x53, 0x63, 0x28, 0x55, 0x61, 0x9c, 0xc0, - 0x2f, 0x0a, 0x98, 0x2e, 0x34, 0x29, 0x2c, 0xdf, 0x49, 0xd2, 0xe8, 0xea, 0xc6, 0x88, 0xd1, 0x02, - 0x6c, 0x8d, 0x83, 0x2d, 0xc3, 0x25, 0x19, 0x58, 0x61, 0x24, 0x70, 0xb2, 0x42, 0xcf, 0x96, 0x93, - 0xc9, 0x1a, 0xbf, 0x9c, 0x4c, 0x3a, 0x08, 0x86, 0x92, 0x15, 0x1b, 0xbb, 0xb9, 0x7d, 0x72, 0x56, - 0x57, 0x4e, 0xcf, 0xea, 0xca, 0x9f, 0xb3, 0xba, 0x72, 0x74, 0x5e, 0xaf, 0x9c, 0x9e, 0xd7, 0x2b, - 0x3f, 0xcf, 0xeb, 0x95, 0x77, 0x77, 0x1d, 0x97, 0xb5, 0x23, 0x4b, 0xdf, 0x23, 0x5d, 0xa3, 0xe7, - 0xb2, 0x8f, 0x2e, 0x4b, 0xdc, 0x36, 0x6c, 0xb4, 0xd1, 0x25, 0x76, 0xe4, 0x61, 0x83, 0x1d, 0x06, - 0x98, 0x5a, 0x93, 0x7c, 0xb0, 0x3c, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, 0x67, 0xde, 0x72, 0xab, - 0x6b, 0x08, 0x00, 0x00, + // 747 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0x4f, 0x6f, 0xd3, 0x3e, + 0x18, 0xc7, 0x9b, 0xed, 0xb7, 0xfd, 0x98, 0xdb, 0xa1, 0xcd, 0xa0, 0x51, 0xc2, 0xd6, 0x76, 0x99, + 0x06, 0x1d, 0x63, 0x09, 0x2b, 0x6f, 0x80, 0x55, 0xa0, 0x71, 0x41, 0x82, 0x0c, 0x81, 0x84, 0x84, + 0x2a, 0x67, 0x31, 0x69, 0xd4, 0x36, 0xce, 0x62, 0xa7, 0x6c, 0x57, 0x8e, 0x9c, 0x26, 0xed, 0x80, + 0xb8, 0xf2, 0x1a, 0x78, 0x11, 0x3b, 0x4e, 0xe2, 0xc2, 0x09, 0xd0, 0xc6, 0x0b, 0x41, 0x71, 0x9c, + 0x2c, 0x69, 0x9d, 0xa9, 0xdc, 0x9a, 0x7e, 0x9f, 0x3f, 0x9f, 0xc7, 0xf6, 0xf7, 0x01, 0x2b, 0xd4, + 0xee, 0x19, 0x68, 0x88, 0xdc, 0xbe, 0x31, 0xdc, 0xb6, 0x30, 0x43, 0xdb, 0xc6, 0x41, 0x88, 0x83, + 0x23, 0xdd, 0x0f, 0x08, 0x23, 0x70, 0x91, 0xda, 0x3d, 0x9d, 0xcb, 0xba, 0x90, 0xd5, 0x9b, 0x0e, + 0x71, 0x08, 0x57, 0x8d, 0xe8, 0x57, 0x1c, 0xa8, 0x2e, 0x3b, 0x84, 0x38, 0x7d, 0x6c, 0x20, 0xdf, + 0x35, 0x90, 0xe7, 0x11, 0x86, 0x98, 0x4b, 0x3c, 0x2a, 0xd4, 0xd5, 0xf1, 0x2e, 0x43, 0xd4, 0x77, + 0x6d, 0xc4, 0x48, 0x20, 0x42, 0xea, 0xa2, 0x00, 0xff, 0xb2, 0xc2, 0xf7, 0x06, 0x73, 0x07, 0x98, + 0x32, 0x34, 0xf0, 0x45, 0x80, 0x3a, 0x5e, 0x83, 0x1d, 0xc6, 0x9a, 0x56, 0x03, 0xcb, 0x2f, 0x23, + 0xea, 0xbd, 0xd0, 0x1a, 0xb8, 0xac, 0xdd, 0x27, 0xd6, 0x1e, 0x43, 0x2c, 0xa4, 0x26, 0x3e, 0x08, + 0x31, 0x65, 0x9a, 0x03, 0x56, 0x0a, 0x74, 0xea, 0x13, 0x8f, 0x62, 0xa8, 0x83, 0x99, 0x00, 0x79, + 0x0e, 0xae, 0x2a, 0x0d, 0xa5, 0x59, 0x6e, 0x55, 0xf5, 0xb1, 0xb9, 0x75, 0x33, 0xd2, 0xcd, 0x38, + 0x0c, 0x2e, 0x81, 0x59, 0xca, 0x2b, 0x54, 0xa7, 0x1a, 0x4a, 0x73, 0xce, 0x14, 0x5f, 0x5a, 0x15, + 0x2c, 0xf1, 0x46, 0xaf, 0x93, 0xe9, 0x52, 0x84, 0x77, 0xe0, 0xd6, 0x98, 0x22, 0x9a, 0xb7, 0x01, + 0x48, 0x4f, 0x83, 0x56, 0x95, 0xc6, 0x74, 0xb3, 0xdc, 0x5a, 0x96, 0x10, 0xa4, 0xa9, 0xed, 0xff, + 0x4e, 0x7f, 0xd6, 0x4b, 0x66, 0x26, 0x4b, 0xdb, 0x05, 0x55, 0x5e, 0x7e, 0x27, 0xca, 0xd8, 0xb1, + 0xed, 0x00, 0xd3, 0xa4, 0x35, 0xdc, 0x04, 0x8b, 0x69, 0x64, 0x07, 0xc5, 0x1a, 0x1f, 0x74, 0xce, + 0x5c, 0x48, 0x05, 0x91, 0xa3, 0x3d, 0x06, 0xb7, 0x25, 0x85, 0x04, 0xe9, 0x1a, 0x98, 0xe7, 0x48, + 0x23, 0x55, 0x2a, 0x28, 0x13, 0xac, 0xa9, 0x02, 0xe5, 0x45, 0x40, 0x86, 0xd8, 0x7b, 0x86, 0x5d, + 0xa7, 0xcb, 0x92, 0x53, 0x48, 0xaa, 0xe7, 0xb5, 0xcb, 0xea, 0x3e, 0xff, 0xbf, 0xd3, 0xe5, 0x02, + 0xaf, 0x3e, 0x6d, 0x56, 0xfc, 0x4c, 0xb0, 0x46, 0xc1, 0x8d, 0x76, 0x9f, 0xec, 0xf7, 0xde, 0xb8, + 0xac, 0xfb, 0xf4, 0xd0, 0x77, 0x03, 0xfe, 0xd0, 0xa2, 0x0b, 0xc9, 0x25, 0x89, 0x2f, 0xf8, 0x04, + 0x00, 0x9c, 0x46, 0xf1, 0xcb, 0x2a, 0xb7, 0x54, 0x3d, 0x7e, 0x6b, 0x7a, 0xf2, 0xd6, 0xf4, 0x57, + 0xc9, 0x5b, 0x6b, 0x5f, 0x8b, 0x4e, 0xf6, 0xf8, 0x57, 0x5d, 0x31, 0x33, 0x79, 0xda, 0x9d, 0x04, + 0x1b, 0x7b, 0xb6, 0xeb, 0x39, 0x1c, 0x20, 0xbd, 0xd9, 0x1e, 0x50, 0x65, 0xa2, 0x18, 0xea, 0x39, + 0xb8, 0xee, 0xc7, 0x42, 0xc7, 0xe2, 0x8a, 0xb8, 0xe0, 0xbb, 0x92, 0x0b, 0x96, 0x0c, 0x66, 0xce, + 0xfb, 0xd9, 0xb2, 0x29, 0x09, 0x8f, 0xc0, 0x76, 0x9e, 0xe4, 0x9b, 0x22, 0x50, 0x46, 0x54, 0x81, + 0xb2, 0x0b, 0x2a, 0xfb, 0x61, 0x10, 0x60, 0x8f, 0x75, 0x22, 0x73, 0x89, 0xb7, 0x3e, 0xd9, 0x69, + 0x94, 0x45, 0x66, 0xa4, 0x45, 0x33, 0xe1, 0xb8, 0x43, 0x32, 0xd3, 0xd4, 0xbf, 0xcd, 0x84, 0xb3, + 0x7c, 0xad, 0x2f, 0xff, 0x83, 0x19, 0x8e, 0x0d, 0xbf, 0x2a, 0x60, 0x61, 0xd4, 0xa3, 0xd0, 0x90, + 0x54, 0xbd, 0xca, 0xed, 0xea, 0xc3, 0xc9, 0x13, 0xe2, 0x93, 0xd1, 0x36, 0x3f, 0x7e, 0xff, 0x73, + 0x32, 0xb5, 0x0e, 0xd7, 0xe2, 0x05, 0x63, 0xf5, 0x89, 0x95, 0x2e, 0x19, 0x3a, 0xca, 0xf3, 0x49, + 0x01, 0xe0, 0xd2, 0xc5, 0x70, 0xa3, 0xa8, 0xdb, 0xd8, 0x0e, 0x50, 0xef, 0x4f, 0x12, 0x2a, 0x90, + 0xd6, 0x39, 0x52, 0x1d, 0xae, 0x48, 0x90, 0x2e, 0x7d, 0x0f, 0x4f, 0x14, 0x50, 0xc9, 0x5a, 0x15, + 0x6e, 0x16, 0xf5, 0x90, 0x6c, 0x06, 0xf5, 0xc1, 0x64, 0xc1, 0x02, 0xa9, 0xc9, 0x91, 0x34, 0xd8, + 0x90, 0x20, 0xe5, 0xd6, 0x02, 0xa7, 0xca, 0x5a, 0xbc, 0x98, 0x4a, 0xb2, 0x24, 0x8a, 0xa9, 0x64, + 0x5b, 0xe3, 0x4a, 0xaa, 0xdc, 0x3a, 0x81, 0x9f, 0x15, 0x30, 0x9f, 0x33, 0x29, 0x2c, 0xee, 0x24, + 0x31, 0xba, 0xba, 0x35, 0x61, 0xb4, 0x00, 0xdb, 0xe0, 0x60, 0x6b, 0x70, 0x55, 0x06, 0x96, 0x5b, + 0x09, 0x9c, 0x2c, 0xe7, 0xd9, 0x62, 0x32, 0x99, 0xf1, 0x8b, 0xc9, 0xa4, 0x8b, 0xe0, 0x4a, 0xb2, + 0xbc, 0xb1, 0xdb, 0x3b, 0xa7, 0xe7, 0x35, 0xe5, 0xec, 0xbc, 0xa6, 0xfc, 0x3e, 0xaf, 0x29, 0xc7, + 0x17, 0xb5, 0xd2, 0xd9, 0x45, 0xad, 0xf4, 0xe3, 0xa2, 0x56, 0x7a, 0x7b, 0xcf, 0x71, 0x59, 0x37, + 0xb4, 0xf4, 0x7d, 0x32, 0x30, 0x86, 0x2e, 0xfb, 0xe0, 0xb2, 0xb8, 0xda, 0x96, 0x8d, 0xb6, 0x06, + 0xc4, 0x0e, 0xfb, 0xd8, 0x60, 0x47, 0x3e, 0xa6, 0xd6, 0x2c, 0x5f, 0x2c, 0x8f, 0xfe, 0x06, 0x00, + 0x00, 0xff, 0xff, 0x92, 0x9d, 0xb6, 0x54, 0x6b, 0x08, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -958,18 +958,6 @@ func (m *QuerySubmitBlobStatusRequest) MarshalToSizedBuffer(dAtA []byte) (int, e _ = i var l int _ = l - if m.Range != nil { - { - size, err := m.Range.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } return len(dAtA) - i, nil } @@ -998,6 +986,18 @@ func (m *QuerySubmitBlobStatusResponse) MarshalToSizedBuffer(dAtA []byte) (int, copy(dAtA[i:], m.Status) i = encodeVarintQuery(dAtA, i, uint64(len(m.Status))) i-- + dAtA[i] = 0x12 + } + if m.Range != nil { + { + size, err := m.Range.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- dAtA[i] = 0xa } return len(dAtA) - i, nil @@ -1355,10 +1355,6 @@ func (m *QuerySubmitBlobStatusRequest) Size() (n int) { } var l int _ = l - if m.Range != nil { - l = m.Range.Size() - n += 1 + l + sovQuery(uint64(l)) - } return n } @@ -1368,6 +1364,10 @@ func (m *QuerySubmitBlobStatusResponse) Size() (n int) { } var l int _ = l + if m.Range != nil { + l = m.Range.Size() + n += 1 + l + sovQuery(uint64(l)) + } l = len(m.Status) if l > 0 { n += 1 + l + sovQuery(uint64(l)) @@ -1545,42 +1545,6 @@ func (m *QuerySubmitBlobStatusRequest) Unmarshal(dAtA []byte) error { return fmt.Errorf("proto: QuerySubmitBlobStatusRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Range", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Range == nil { - m.Range = &Range{} - } - if err := m.Range.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) @@ -1632,6 +1596,42 @@ func (m *QuerySubmitBlobStatusResponse) Unmarshal(dAtA []byte) error { } switch fieldNum { case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Range", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Range == nil { + m.Range = &Range{} + } + if err := m.Range.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) } diff --git a/types/query.pb.gw.go b/types/query.pb.gw.go index ab4ef83..82b8a1d 100644 --- a/types/query.pb.gw.go +++ b/types/query.pb.gw.go @@ -33,21 +33,10 @@ var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage var _ = metadata.Join -var ( - filter_Query_SubmitBlobStatus_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - func request_Query_SubmitBlobStatus_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq QuerySubmitBlobStatusRequest var metadata runtime.ServerMetadata - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SubmitBlobStatus_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - msg, err := client.SubmitBlobStatus(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err @@ -57,13 +46,6 @@ func local_request_Query_SubmitBlobStatus_0(ctx context.Context, marshaler runti var protoReq QuerySubmitBlobStatusRequest var metadata runtime.ServerMetadata - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SubmitBlobStatus_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - msg, err := server.SubmitBlobStatus(ctx, &protoReq) return msg, metadata, err From 072db7c71faa1310c4c98c1539d7df5a87d46158 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Tue, 3 Sep 2024 10:33:40 +0530 Subject: [PATCH 28/58] update msg --- relayer/publish.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/relayer/publish.go b/relayer/publish.go index 2d4cd58..41b5549 100644 --- a/relayer/publish.go +++ b/relayer/publish.go @@ -122,16 +122,18 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo fmt.Println("proposer addressss........", sdk.AccAddress.String(proposer), uint64(blocks[0]), uint64(blocks[len(blocks)-1]), uint64(blockInfo.BlockNumber)) - // TODO : execute tx about successfull submission - err = ExecuteTX(ctx, types.MsgUpdateBlobStatusRequest{ - ValidatorAddress: sdk.AccAddress.String(proposer), + msg := types.MsgUpdateBlobStatusRequest{ValidatorAddress: sdk.AccAddress.String(proposer), BlocksRange: &types.Range{ From: uint64(blocks[0]), To: uint64(blocks[len(blocks)-1]), }, AvailHeight: uint64(blockInfo.BlockNumber), - IsSuccess: true, - }, cdc) + IsSuccess: true} + + fmt.Println("submit blocks msg.......", msg) + + // TODO : execute tx about successfull submission + err = ExecuteTX(ctx, msg, cdc) if err != nil { fmt.Println("error while submitting tx...", err) } From 05702ffa81250717c3f113e0a42067d8333d8465 Mon Sep 17 00:00:00 2001 From: saiteja Date: Tue, 3 Sep 2024 11:22:21 +0530 Subject: [PATCH 29/58] feat: fixed range errors --- keeper/abci.go | 11 +-- keeper/collections.go | 4 +- keeper/genesis.go | 6 +- keeper/keeper.go | 7 +- proto/sdk/avail/v1beta1/genesis.proto | 2 +- proto/sdk/avail/v1beta1/query.proto | 2 +- relayer/publish.go | 5 +- types/genesis.pb.go | 46 ++++++------ types/query.pb.go | 102 +++++++++++++------------- 9 files changed, 94 insertions(+), 91 deletions(-) diff --git a/keeper/abci.go b/keeper/abci.go index 0481215..a9b907a 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -54,13 +54,14 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err fmt.Println("block heighttt.........", ctx.BlockHeight(), ctx.ExecMode(), ctx.IsCheckTx(), ctx.IsReCheckTx()) - fromHeight := k.GetProvenHeightFromStore(ctx) //Todo: change this get from ProvenHeight from store + provenHeight := k.GetProvenHeightFromStore(ctx) + fromHeight := provenHeight + 1 fmt.Println("from height..", fromHeight) - endHeight := min(fromHeight+uint64(k.MaxBlocksForBlob), uint64(ctx.BlockHeight())) - fmt.Println("end height..", endHeight) + endHeight := min(fromHeight+uint64(k.MaxBlocksForBlob), uint64(ctx.BlockHeight())) //exclusive i.e [fromHeight, endHeight) + fmt.Println("end height..", endHeight-1) sdkCtx := sdk.UnwrapSDKContext(ctx) - err := k.SetBlobStatusPending(sdkCtx, fromHeight, endHeight) + err := k.SetBlobStatusPending(sdkCtx, fromHeight, endHeight-1) if err != nil { fmt.Println("error while setting blob status...", err) return nil @@ -68,7 +69,7 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err var blocksToSumit []int64 - for i := fromHeight + 1; i < endHeight; i++ { + for i := fromHeight; i < endHeight; i++ { blocksToSumit = append(blocksToSumit, int64(i)) } diff --git a/keeper/collections.go b/keeper/collections.go index eec90c5..82a81d4 100644 --- a/keeper/collections.go +++ b/keeper/collections.go @@ -50,11 +50,11 @@ func (k *Keeper) GetAllValidators(ctx context.Context) (types.Validators, error) return validators, nil } -func (k *Keeper) SetProvenHeight(ctx context.Context, height int64) error { +func (k *Keeper) SetProvenHeight(ctx context.Context, height uint64) error { return k.ProvenHeight.Set(ctx, height) } -func (k *Keeper) GetProvenHeight(ctx context.Context) (int64, error) { +func (k *Keeper) GetProvenHeight(ctx context.Context) (uint64, error) { return k.ProvenHeight.Get(ctx) } diff --git a/keeper/genesis.go b/keeper/genesis.go index 03f336b..d5e99e4 100644 --- a/keeper/genesis.go +++ b/keeper/genesis.go @@ -14,9 +14,9 @@ func (k *Keeper) InitGenesis(ctx sdk.Context, data *types.GenesisState) error { } // Set proven height to genesis height, we do not init any pending block on a genesis init/restart - if err := k.SetProvenHeight(ctx, ctx.HeaderInfo().Height); err != nil { - return err - } + // if err := k.SetProvenHeight(ctx, ctx.HeaderInfo().Height); err != nil { + // return err + // } k.relayer.NotifyProvenHeight(ctx.HeaderInfo().Height) diff --git a/keeper/keeper.go b/keeper/keeper.go index 2f192d6..32623e5 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -30,7 +30,7 @@ type Keeper struct { Validators collections.Map[string, string] ClientID collections.Item[string] - ProvenHeight collections.Item[int64] + ProvenHeight collections.Item[uint64] PendingBlocksToTimeouts collections.Map[int64, int64] TimeoutsToPendingBlocks collections.Map[int64, types.PendingBlocks] keyring keyring.Keyring @@ -70,7 +70,7 @@ func NewKeeper( Validators: collections.NewMap(sb, availblob1.ValidatorsKey, "validators", collections.StringKey, collections.StringValue), ClientID: collections.NewItem(sb, availblob1.ClientIDKey, "client_id", collections.StringValue), - ProvenHeight: collections.NewItem(sb, availblob1.ProvenHeightKey, "proven_height", collections.Int64Value), + ProvenHeight: collections.NewItem(sb, availblob1.ProvenHeightKey, "proven_height", collections.Uint64Value), PendingBlocksToTimeouts: collections.NewMap(sb, availblob1.PendingBlocksToTimeouts, "pending_blocks_to_timeouts", collections.Int64Key, collections.Int64Value), TimeoutsToPendingBlocks: collections.NewMap(sb, availblob1.TimeoutsToPendingBlocks, "timeouts_to_pending_blocks", collections.Int64Key, codec.CollValue[types.PendingBlocks](cdc)), @@ -161,7 +161,8 @@ func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatu status := GetStatusFromStore(store) if req.BlocksRange.From != provenHeight+1 || req.BlocksRange.To != endHeight { - return nil, errors.New("invalid blocks range") + return nil, fmt.Errorf("invalid blocks range request: expected range [%d -> %d], got [%d -> %d]", + provenHeight+1, endHeight, req.BlocksRange.From, req.BlocksRange.To) } if status != PENDING_STATE { diff --git a/proto/sdk/avail/v1beta1/genesis.proto b/proto/sdk/avail/v1beta1/genesis.proto index 8c7bbe1..39cb7c2 100644 --- a/proto/sdk/avail/v1beta1/genesis.proto +++ b/proto/sdk/avail/v1beta1/genesis.proto @@ -12,6 +12,6 @@ message GenesisState { // the height of the last block that was proven to be posted to Avail. // increment only, never skipping heights. - int64 proven_height = 2; + uint64 proven_height = 2; repeated BlockWithExpiration pending_blocks = 3; } \ No newline at end of file diff --git a/proto/sdk/avail/v1beta1/query.proto b/proto/sdk/avail/v1beta1/query.proto index ee88aec..f3f0d7b 100644 --- a/proto/sdk/avail/v1beta1/query.proto +++ b/proto/sdk/avail/v1beta1/query.proto @@ -79,7 +79,7 @@ message QueryAvailAddressResponse { message QueryProvenHeightRequest {} message QueryProvenHeightResponse { - int64 proven_height = 1; + uint64 proven_height = 1; } message BlockWithExpiration { diff --git a/relayer/publish.go b/relayer/publish.go index 2d4cd58..e365aa4 100644 --- a/relayer/publish.go +++ b/relayer/publish.go @@ -142,7 +142,7 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo func ExecuteTX(ctx sdk.Context, msg types.MsgUpdateBlobStatusRequest, cdc codec.BinaryCodec) error { // Define keyring and RPC client configuration - homePath := "/home/vitwit/.availsdk" + homePath := "/home/vitwit/.simapp" keyName := "alice" rpcAddress := "http://localhost:26657" @@ -160,8 +160,9 @@ func ExecuteTX(ctx sdk.Context, msg types.MsgUpdateBlobStatusRequest, cdc codec. info, err := kr.Key(keyName) // log.Println("uuu....", info, err) - + fmt.Println("here error???", info == nil) valAddr, err := info.GetAddress() + fmt.Println("after address................", valAddr) // valAddr, err := sdk.AccAddressFromBech32(addr.String()) // fmt.Println("val addr, err..", valAddr, err, addr) diff --git a/types/genesis.pb.go b/types/genesis.pb.go index e94ec58..b470a5f 100644 --- a/types/genesis.pb.go +++ b/types/genesis.pb.go @@ -28,7 +28,7 @@ type GenesisState struct { Validators []Validator `protobuf:"bytes,1,rep,name=validators,proto3" json:"validators"` // the height of the last block that was proven to be posted to Avail. // increment only, never skipping heights. - ProvenHeight int64 `protobuf:"varint,2,opt,name=proven_height,json=provenHeight,proto3" json:"proven_height,omitempty"` + ProvenHeight uint64 `protobuf:"varint,2,opt,name=proven_height,json=provenHeight,proto3" json:"proven_height,omitempty"` PendingBlocks []*BlockWithExpiration `protobuf:"bytes,3,rep,name=pending_blocks,json=pendingBlocks,proto3" json:"pending_blocks,omitempty"` } @@ -72,7 +72,7 @@ func (m *GenesisState) GetValidators() []Validator { return nil } -func (m *GenesisState) GetProvenHeight() int64 { +func (m *GenesisState) GetProvenHeight() uint64 { if m != nil { return m.ProvenHeight } @@ -93,26 +93,26 @@ func init() { func init() { proto.RegisterFile("sdk/avail/v1beta1/genesis.proto", fileDescriptor_b83d128538762178) } var fileDescriptor_b83d128538762178 = []byte{ - // 298 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0x41, 0x4b, 0xc3, 0x30, - 0x1c, 0xc5, 0x1b, 0x27, 0x1e, 0xe2, 0x26, 0x58, 0x3c, 0x8c, 0xa1, 0xd9, 0x54, 0xd0, 0x5d, 0x96, - 0x30, 0xfd, 0x04, 0x16, 0x44, 0x2f, 0x5e, 0x26, 0x28, 0x78, 0x19, 0xe9, 0x12, 0xd2, 0xb0, 0xae, - 0xa9, 0xcd, 0x7f, 0xd5, 0x7d, 0x0b, 0x3f, 0x95, 0xec, 0xb8, 0xa3, 0x27, 0x91, 0xf5, 0x8b, 0xc8, - 0xd2, 0x2a, 0x42, 0xbd, 0x85, 0xff, 0xfb, 0xbd, 0xf7, 0xc2, 0xc3, 0x5d, 0x2b, 0xa6, 0x8c, 0xe7, - 0x5c, 0xc7, 0x2c, 0x1f, 0x86, 0x12, 0xf8, 0x90, 0x29, 0x99, 0x48, 0xab, 0x2d, 0x4d, 0x33, 0x03, - 0xc6, 0xdf, 0xb7, 0x62, 0x4a, 0x1d, 0x40, 0x2b, 0xa0, 0x73, 0xa0, 0x8c, 0x32, 0x4e, 0x65, 0x9b, - 0x57, 0x09, 0x76, 0x8e, 0xeb, 0x49, 0x39, 0x8f, 0xb5, 0xe0, 0x60, 0xb2, 0x0a, 0x39, 0xaa, 0x23, - 0xcf, 0x73, 0x99, 0x2d, 0x4a, 0xf9, 0xe4, 0x1d, 0xe1, 0xe6, 0x4d, 0x59, 0x7e, 0x0f, 0x1c, 0xa4, - 0x1f, 0x60, 0xfc, 0x1b, 0x61, 0xdb, 0xa8, 0xd7, 0xe8, 0xef, 0x5e, 0x1c, 0xd2, 0xda, 0x87, 0xe8, - 0xc3, 0x0f, 0x14, 0x6c, 0x2f, 0x3f, 0xbb, 0xde, 0xe8, 0x8f, 0xcb, 0x3f, 0xc5, 0xad, 0x34, 0x33, - 0xb9, 0x4c, 0xc6, 0x91, 0xd4, 0x2a, 0x82, 0xf6, 0x56, 0x0f, 0xf5, 0x1b, 0xa3, 0x66, 0x79, 0xbc, - 0x75, 0x37, 0xff, 0x0e, 0xef, 0xa5, 0x32, 0x11, 0x3a, 0x51, 0xe3, 0x30, 0x36, 0x93, 0xa9, 0x6d, - 0x37, 0x5c, 0xd9, 0xd9, 0x3f, 0x65, 0xc1, 0x06, 0x78, 0xd4, 0x10, 0x5d, 0xbf, 0xa6, 0x3a, 0xe3, - 0xa0, 0x4d, 0x32, 0x6a, 0x55, 0x6e, 0xa7, 0xd9, 0xe0, 0x6a, 0xb9, 0x26, 0x68, 0xb5, 0x26, 0xe8, - 0x6b, 0x4d, 0xd0, 0x5b, 0x41, 0xbc, 0x55, 0x41, 0xbc, 0x8f, 0x82, 0x78, 0x4f, 0xe7, 0x4a, 0x43, - 0x34, 0x0f, 0xe9, 0xc4, 0xcc, 0x58, 0xae, 0xe1, 0x45, 0x43, 0xb9, 0xc7, 0x40, 0xf0, 0xc1, 0xcc, - 0x88, 0x79, 0x2c, 0x19, 0x2c, 0x52, 0x69, 0xc3, 0x1d, 0x37, 0xc9, 0xe5, 0x77, 0x00, 0x00, 0x00, - 0xff, 0xff, 0x66, 0x8c, 0xe9, 0x95, 0xa0, 0x01, 0x00, 0x00, + // 299 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0x41, 0x4b, 0xf3, 0x30, + 0x1c, 0xc6, 0x9b, 0x77, 0xe3, 0x3d, 0xc4, 0x4d, 0xb0, 0x78, 0x18, 0x43, 0xb3, 0xa9, 0xa0, 0xbb, + 0x2c, 0x61, 0xfa, 0x09, 0x2c, 0x88, 0x5e, 0xbc, 0x4c, 0x50, 0xf0, 0x32, 0xd2, 0x25, 0xa4, 0x61, + 0x5d, 0x53, 0x9b, 0xff, 0xaa, 0xfb, 0x16, 0x7e, 0x2a, 0xd9, 0x71, 0x47, 0x4f, 0x22, 0xeb, 0x17, + 0x91, 0xa5, 0x55, 0x84, 0x7a, 0x0b, 0xff, 0xe7, 0xf7, 0x3c, 0x4f, 0x78, 0x70, 0xcf, 0x8a, 0x19, + 0xe3, 0x39, 0xd7, 0x31, 0xcb, 0x47, 0xa1, 0x04, 0x3e, 0x62, 0x4a, 0x26, 0xd2, 0x6a, 0x4b, 0xd3, + 0xcc, 0x80, 0xf1, 0xf7, 0xac, 0x98, 0x51, 0x07, 0xd0, 0x0a, 0xe8, 0xee, 0x2b, 0xa3, 0x8c, 0x53, + 0xd9, 0xf6, 0x55, 0x82, 0xdd, 0xa3, 0x7a, 0x52, 0xce, 0x63, 0x2d, 0x38, 0x98, 0xac, 0x42, 0x0e, + 0xeb, 0xc8, 0xd3, 0x42, 0x66, 0xcb, 0x52, 0x3e, 0x7e, 0x43, 0xb8, 0x75, 0x5d, 0x96, 0xdf, 0x01, + 0x07, 0xe9, 0x07, 0x18, 0xff, 0x44, 0xd8, 0x0e, 0xea, 0x37, 0x06, 0x3b, 0xe7, 0x07, 0xb4, 0xf6, + 0x21, 0x7a, 0xff, 0x0d, 0x05, 0xcd, 0xd5, 0x47, 0xcf, 0x1b, 0xff, 0x72, 0xf9, 0x27, 0xb8, 0x9d, + 0x66, 0x26, 0x97, 0xc9, 0x24, 0x92, 0x5a, 0x45, 0xd0, 0xf9, 0xd7, 0x47, 0x83, 0xe6, 0xb8, 0x55, + 0x1e, 0x6f, 0xdc, 0xcd, 0xbf, 0xc5, 0xbb, 0xa9, 0x4c, 0x84, 0x4e, 0xd4, 0x24, 0x8c, 0xcd, 0x74, + 0x66, 0x3b, 0x0d, 0x57, 0x76, 0xfa, 0x47, 0x59, 0xb0, 0x05, 0x1e, 0x34, 0x44, 0x57, 0x2f, 0xa9, + 0xce, 0x38, 0x68, 0x93, 0x8c, 0xdb, 0x95, 0xdb, 0x69, 0x36, 0xb8, 0x5c, 0x6d, 0x08, 0x5a, 0x6f, + 0x08, 0xfa, 0xdc, 0x10, 0xf4, 0x5a, 0x10, 0x6f, 0x5d, 0x10, 0xef, 0xbd, 0x20, 0xde, 0xe3, 0x99, + 0xd2, 0x10, 0x2d, 0x42, 0x3a, 0x35, 0x73, 0x96, 0x6b, 0x78, 0xd6, 0x50, 0xee, 0x31, 0x14, 0x7c, + 0x38, 0x37, 0x62, 0x11, 0x4b, 0x06, 0xcb, 0x54, 0xda, 0xf0, 0xbf, 0x9b, 0xe4, 0xe2, 0x2b, 0x00, + 0x00, 0xff, 0xff, 0x1c, 0x97, 0x0b, 0x5a, 0xa0, 0x01, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { @@ -289,7 +289,7 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.ProvenHeight |= int64(b&0x7F) << shift + m.ProvenHeight |= uint64(b&0x7F) << shift if b < 0x80 { break } diff --git a/types/query.pb.go b/types/query.pb.go index 94c269a..cc0c50c 100644 --- a/types/query.pb.go +++ b/types/query.pb.go @@ -334,7 +334,7 @@ func (m *QueryProvenHeightRequest) XXX_DiscardUnknown() { var xxx_messageInfo_QueryProvenHeightRequest proto.InternalMessageInfo type QueryProvenHeightResponse struct { - ProvenHeight int64 `protobuf:"varint,1,opt,name=proven_height,json=provenHeight,proto3" json:"proven_height,omitempty"` + ProvenHeight uint64 `protobuf:"varint,1,opt,name=proven_height,json=provenHeight,proto3" json:"proven_height,omitempty"` } func (m *QueryProvenHeightResponse) Reset() { *m = QueryProvenHeightResponse{} } @@ -370,7 +370,7 @@ func (m *QueryProvenHeightResponse) XXX_DiscardUnknown() { var xxx_messageInfo_QueryProvenHeightResponse proto.InternalMessageInfo -func (m *QueryProvenHeightResponse) GetProvenHeight() int64 { +func (m *QueryProvenHeightResponse) GetProvenHeight() uint64 { if m != nil { return m.ProvenHeight } @@ -616,54 +616,54 @@ func init() { func init() { proto.RegisterFile("sdk/avail/v1beta1/query.proto", fileDescriptor_30ff5d91ce731c68) } var fileDescriptor_30ff5d91ce731c68 = []byte{ - // 747 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0x4f, 0x6f, 0xd3, 0x3e, - 0x18, 0xc7, 0x9b, 0xed, 0xb7, 0xfd, 0x98, 0xdb, 0xa1, 0xcd, 0xa0, 0x51, 0xc2, 0xd6, 0x76, 0x99, - 0x06, 0x1d, 0x63, 0x09, 0x2b, 0x6f, 0x80, 0x55, 0xa0, 0x71, 0x41, 0x82, 0x0c, 0x81, 0x84, 0x84, - 0x2a, 0x67, 0x31, 0x69, 0xd4, 0x36, 0xce, 0x62, 0xa7, 0x6c, 0x57, 0x8e, 0x9c, 0x26, 0xed, 0x80, - 0xb8, 0xf2, 0x1a, 0x78, 0x11, 0x3b, 0x4e, 0xe2, 0xc2, 0x09, 0xd0, 0xc6, 0x0b, 0x41, 0x71, 0x9c, - 0x2c, 0x69, 0x9d, 0xa9, 0xdc, 0x9a, 0x7e, 0x9f, 0x3f, 0x9f, 0xc7, 0xf6, 0xf7, 0x01, 0x2b, 0xd4, - 0xee, 0x19, 0x68, 0x88, 0xdc, 0xbe, 0x31, 0xdc, 0xb6, 0x30, 0x43, 0xdb, 0xc6, 0x41, 0x88, 0x83, - 0x23, 0xdd, 0x0f, 0x08, 0x23, 0x70, 0x91, 0xda, 0x3d, 0x9d, 0xcb, 0xba, 0x90, 0xd5, 0x9b, 0x0e, - 0x71, 0x08, 0x57, 0x8d, 0xe8, 0x57, 0x1c, 0xa8, 0x2e, 0x3b, 0x84, 0x38, 0x7d, 0x6c, 0x20, 0xdf, - 0x35, 0x90, 0xe7, 0x11, 0x86, 0x98, 0x4b, 0x3c, 0x2a, 0xd4, 0xd5, 0xf1, 0x2e, 0x43, 0xd4, 0x77, - 0x6d, 0xc4, 0x48, 0x20, 0x42, 0xea, 0xa2, 0x00, 0xff, 0xb2, 0xc2, 0xf7, 0x06, 0x73, 0x07, 0x98, - 0x32, 0x34, 0xf0, 0x45, 0x80, 0x3a, 0x5e, 0x83, 0x1d, 0xc6, 0x9a, 0x56, 0x03, 0xcb, 0x2f, 0x23, - 0xea, 0xbd, 0xd0, 0x1a, 0xb8, 0xac, 0xdd, 0x27, 0xd6, 0x1e, 0x43, 0x2c, 0xa4, 0x26, 0x3e, 0x08, - 0x31, 0x65, 0x9a, 0x03, 0x56, 0x0a, 0x74, 0xea, 0x13, 0x8f, 0x62, 0xa8, 0x83, 0x99, 0x00, 0x79, - 0x0e, 0xae, 0x2a, 0x0d, 0xa5, 0x59, 0x6e, 0x55, 0xf5, 0xb1, 0xb9, 0x75, 0x33, 0xd2, 0xcd, 0x38, - 0x0c, 0x2e, 0x81, 0x59, 0xca, 0x2b, 0x54, 0xa7, 0x1a, 0x4a, 0x73, 0xce, 0x14, 0x5f, 0x5a, 0x15, - 0x2c, 0xf1, 0x46, 0xaf, 0x93, 0xe9, 0x52, 0x84, 0x77, 0xe0, 0xd6, 0x98, 0x22, 0x9a, 0xb7, 0x01, - 0x48, 0x4f, 0x83, 0x56, 0x95, 0xc6, 0x74, 0xb3, 0xdc, 0x5a, 0x96, 0x10, 0xa4, 0xa9, 0xed, 0xff, - 0x4e, 0x7f, 0xd6, 0x4b, 0x66, 0x26, 0x4b, 0xdb, 0x05, 0x55, 0x5e, 0x7e, 0x27, 0xca, 0xd8, 0xb1, - 0xed, 0x00, 0xd3, 0xa4, 0x35, 0xdc, 0x04, 0x8b, 0x69, 0x64, 0x07, 0xc5, 0x1a, 0x1f, 0x74, 0xce, - 0x5c, 0x48, 0x05, 0x91, 0xa3, 0x3d, 0x06, 0xb7, 0x25, 0x85, 0x04, 0xe9, 0x1a, 0x98, 0xe7, 0x48, - 0x23, 0x55, 0x2a, 0x28, 0x13, 0xac, 0xa9, 0x02, 0xe5, 0x45, 0x40, 0x86, 0xd8, 0x7b, 0x86, 0x5d, - 0xa7, 0xcb, 0x92, 0x53, 0x48, 0xaa, 0xe7, 0xb5, 0xcb, 0xea, 0x3e, 0xff, 0xbf, 0xd3, 0xe5, 0x02, - 0xaf, 0x3e, 0x6d, 0x56, 0xfc, 0x4c, 0xb0, 0x46, 0xc1, 0x8d, 0x76, 0x9f, 0xec, 0xf7, 0xde, 0xb8, - 0xac, 0xfb, 0xf4, 0xd0, 0x77, 0x03, 0xfe, 0xd0, 0xa2, 0x0b, 0xc9, 0x25, 0x89, 0x2f, 0xf8, 0x04, - 0x00, 0x9c, 0x46, 0xf1, 0xcb, 0x2a, 0xb7, 0x54, 0x3d, 0x7e, 0x6b, 0x7a, 0xf2, 0xd6, 0xf4, 0x57, - 0xc9, 0x5b, 0x6b, 0x5f, 0x8b, 0x4e, 0xf6, 0xf8, 0x57, 0x5d, 0x31, 0x33, 0x79, 0xda, 0x9d, 0x04, - 0x1b, 0x7b, 0xb6, 0xeb, 0x39, 0x1c, 0x20, 0xbd, 0xd9, 0x1e, 0x50, 0x65, 0xa2, 0x18, 0xea, 0x39, - 0xb8, 0xee, 0xc7, 0x42, 0xc7, 0xe2, 0x8a, 0xb8, 0xe0, 0xbb, 0x92, 0x0b, 0x96, 0x0c, 0x66, 0xce, - 0xfb, 0xd9, 0xb2, 0x29, 0x09, 0x8f, 0xc0, 0x76, 0x9e, 0xe4, 0x9b, 0x22, 0x50, 0x46, 0x54, 0x81, - 0xb2, 0x0b, 0x2a, 0xfb, 0x61, 0x10, 0x60, 0x8f, 0x75, 0x22, 0x73, 0x89, 0xb7, 0x3e, 0xd9, 0x69, - 0x94, 0x45, 0x66, 0xa4, 0x45, 0x33, 0xe1, 0xb8, 0x43, 0x32, 0xd3, 0xd4, 0xbf, 0xcd, 0x84, 0xb3, - 0x7c, 0xad, 0x2f, 0xff, 0x83, 0x19, 0x8e, 0x0d, 0xbf, 0x2a, 0x60, 0x61, 0xd4, 0xa3, 0xd0, 0x90, - 0x54, 0xbd, 0xca, 0xed, 0xea, 0xc3, 0xc9, 0x13, 0xe2, 0x93, 0xd1, 0x36, 0x3f, 0x7e, 0xff, 0x73, - 0x32, 0xb5, 0x0e, 0xd7, 0xe2, 0x05, 0x63, 0xf5, 0x89, 0x95, 0x2e, 0x19, 0x3a, 0xca, 0xf3, 0x49, - 0x01, 0xe0, 0xd2, 0xc5, 0x70, 0xa3, 0xa8, 0xdb, 0xd8, 0x0e, 0x50, 0xef, 0x4f, 0x12, 0x2a, 0x90, - 0xd6, 0x39, 0x52, 0x1d, 0xae, 0x48, 0x90, 0x2e, 0x7d, 0x0f, 0x4f, 0x14, 0x50, 0xc9, 0x5a, 0x15, - 0x6e, 0x16, 0xf5, 0x90, 0x6c, 0x06, 0xf5, 0xc1, 0x64, 0xc1, 0x02, 0xa9, 0xc9, 0x91, 0x34, 0xd8, - 0x90, 0x20, 0xe5, 0xd6, 0x02, 0xa7, 0xca, 0x5a, 0xbc, 0x98, 0x4a, 0xb2, 0x24, 0x8a, 0xa9, 0x64, - 0x5b, 0xe3, 0x4a, 0xaa, 0xdc, 0x3a, 0x81, 0x9f, 0x15, 0x30, 0x9f, 0x33, 0x29, 0x2c, 0xee, 0x24, - 0x31, 0xba, 0xba, 0x35, 0x61, 0xb4, 0x00, 0xdb, 0xe0, 0x60, 0x6b, 0x70, 0x55, 0x06, 0x96, 0x5b, - 0x09, 0x9c, 0x2c, 0xe7, 0xd9, 0x62, 0x32, 0x99, 0xf1, 0x8b, 0xc9, 0xa4, 0x8b, 0xe0, 0x4a, 0xb2, - 0xbc, 0xb1, 0xdb, 0x3b, 0xa7, 0xe7, 0x35, 0xe5, 0xec, 0xbc, 0xa6, 0xfc, 0x3e, 0xaf, 0x29, 0xc7, - 0x17, 0xb5, 0xd2, 0xd9, 0x45, 0xad, 0xf4, 0xe3, 0xa2, 0x56, 0x7a, 0x7b, 0xcf, 0x71, 0x59, 0x37, - 0xb4, 0xf4, 0x7d, 0x32, 0x30, 0x86, 0x2e, 0xfb, 0xe0, 0xb2, 0xb8, 0xda, 0x96, 0x8d, 0xb6, 0x06, - 0xc4, 0x0e, 0xfb, 0xd8, 0x60, 0x47, 0x3e, 0xa6, 0xd6, 0x2c, 0x5f, 0x2c, 0x8f, 0xfe, 0x06, 0x00, - 0x00, 0xff, 0xff, 0x92, 0x9d, 0xb6, 0x54, 0x6b, 0x08, 0x00, 0x00, + // 749 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xcd, 0x6e, 0xd3, 0x4a, + 0x14, 0xc7, 0xe3, 0x7e, 0xdd, 0xdb, 0x49, 0x7a, 0xd5, 0xce, 0x45, 0x25, 0x98, 0x36, 0x49, 0x5d, + 0x15, 0x52, 0x4a, 0x6d, 0x1a, 0x5e, 0x80, 0x46, 0xa0, 0xb2, 0x41, 0x02, 0x17, 0x81, 0x84, 0x84, + 0xa2, 0x71, 0x3d, 0x38, 0x56, 0x12, 0x8f, 0xeb, 0x19, 0x87, 0x76, 0xcb, 0x92, 0x55, 0xa5, 0x2e, + 0x10, 0x5b, 0x9e, 0x81, 0x87, 0xe8, 0xb2, 0x12, 0x1b, 0x56, 0x80, 0x5a, 0x1e, 0x04, 0x79, 0x3c, + 0x76, 0xed, 0x64, 0x5c, 0x85, 0x5d, 0x9c, 0xff, 0xf9, 0xf8, 0x9d, 0x99, 0xf9, 0x1f, 0xb0, 0x4a, + 0xed, 0x9e, 0x81, 0x86, 0xc8, 0xed, 0x1b, 0xc3, 0x1d, 0x0b, 0x33, 0xb4, 0x63, 0x1c, 0x86, 0x38, + 0x38, 0xd6, 0xfd, 0x80, 0x30, 0x02, 0x97, 0xa8, 0xdd, 0xd3, 0xb9, 0xac, 0x0b, 0x59, 0xbd, 0xe1, + 0x10, 0x87, 0x70, 0xd5, 0x88, 0x7e, 0xc5, 0x81, 0xea, 0x8a, 0x43, 0x88, 0xd3, 0xc7, 0x06, 0xf2, + 0x5d, 0x03, 0x79, 0x1e, 0x61, 0x88, 0xb9, 0xc4, 0xa3, 0x42, 0x5d, 0x1b, 0xef, 0x32, 0x44, 0x7d, + 0xd7, 0x46, 0x8c, 0x04, 0x22, 0xa4, 0x2e, 0x0a, 0xf0, 0x2f, 0x2b, 0x7c, 0x67, 0x30, 0x77, 0x80, + 0x29, 0x43, 0x03, 0x5f, 0x04, 0xa8, 0xe3, 0x35, 0xd8, 0x51, 0xac, 0x69, 0x35, 0xb0, 0xf2, 0x22, + 0xa2, 0xde, 0x0f, 0xad, 0x81, 0xcb, 0xda, 0x7d, 0x62, 0xed, 0x33, 0xc4, 0x42, 0x6a, 0xe2, 0xc3, + 0x10, 0x53, 0xa6, 0x39, 0x60, 0xb5, 0x40, 0xa7, 0x3e, 0xf1, 0x28, 0x86, 0x3a, 0x98, 0x0d, 0x90, + 0xe7, 0xe0, 0xaa, 0xd2, 0x50, 0x9a, 0xe5, 0x56, 0x55, 0x1f, 0x9b, 0x5b, 0x37, 0x23, 0xdd, 0x8c, + 0xc3, 0xe0, 0x32, 0x98, 0xa3, 0xbc, 0x42, 0x75, 0xaa, 0xa1, 0x34, 0xe7, 0x4d, 0xf1, 0xa5, 0x55, + 0xc1, 0x32, 0x6f, 0xf4, 0x2a, 0x99, 0x2e, 0x45, 0x78, 0x0b, 0x6e, 0x8e, 0x29, 0xa2, 0x79, 0x1b, + 0x80, 0xf4, 0x34, 0x68, 0x55, 0x69, 0x4c, 0x37, 0xcb, 0xad, 0x15, 0x09, 0x41, 0x9a, 0xda, 0x9e, + 0x39, 0xfb, 0x51, 0x2f, 0x99, 0x99, 0x2c, 0x6d, 0x0f, 0x54, 0x79, 0xf9, 0xdd, 0x28, 0x63, 0xd7, + 0xb6, 0x03, 0x4c, 0x93, 0xd6, 0x70, 0x0b, 0x2c, 0xa5, 0x91, 0x1d, 0x14, 0x6b, 0x7c, 0xd0, 0x79, + 0x73, 0x31, 0x15, 0x44, 0x8e, 0xf6, 0x08, 0xdc, 0x92, 0x14, 0x12, 0xa4, 0xeb, 0x60, 0x81, 0x23, + 0x8d, 0x54, 0xa9, 0xa0, 0x4c, 0xb0, 0xa6, 0x0a, 0x94, 0xe7, 0x01, 0x19, 0x62, 0xef, 0x29, 0x76, + 0x9d, 0x2e, 0x4b, 0x4e, 0x21, 0xa9, 0x9e, 0xd7, 0xae, 0xaa, 0xfb, 0xfc, 0xff, 0x4e, 0x97, 0x0b, + 0xbc, 0xfa, 0x8c, 0x59, 0xf1, 0x33, 0xc1, 0x1a, 0x05, 0xff, 0xb7, 0xfb, 0xe4, 0xa0, 0xf7, 0xda, + 0x65, 0xdd, 0x27, 0x47, 0xbe, 0x1b, 0xf0, 0x87, 0x16, 0x5d, 0x48, 0x26, 0x69, 0xda, 0x14, 0x5f, + 0xf0, 0x31, 0x00, 0x38, 0x8d, 0xe2, 0x97, 0x55, 0x6e, 0xa9, 0x7a, 0xfc, 0xd6, 0xf4, 0xe4, 0xad, + 0xe9, 0x2f, 0x93, 0xb7, 0xd6, 0xfe, 0x37, 0x3a, 0xd9, 0x93, 0x9f, 0x75, 0xc5, 0xcc, 0xe4, 0x69, + 0xb7, 0x13, 0x6c, 0xec, 0xd9, 0xae, 0xe7, 0x70, 0x80, 0xf4, 0x66, 0x7b, 0x40, 0x95, 0x89, 0x62, + 0xa8, 0x67, 0xe0, 0x3f, 0x3f, 0x16, 0x3a, 0x16, 0x57, 0xc4, 0x05, 0xdf, 0x91, 0x5c, 0xb0, 0x64, + 0x30, 0x73, 0xc1, 0xcf, 0x96, 0x4d, 0x49, 0x78, 0x04, 0xb6, 0xf3, 0x24, 0x5f, 0x15, 0x81, 0x32, + 0xa2, 0x0a, 0x94, 0x3d, 0x50, 0x39, 0x08, 0x83, 0x00, 0x7b, 0xac, 0x13, 0x99, 0x4b, 0xbc, 0xf5, + 0xc9, 0x4e, 0xa3, 0x2c, 0x32, 0x23, 0x2d, 0x9a, 0x09, 0xc7, 0x1d, 0x92, 0x99, 0xa6, 0xfe, 0x6e, + 0x26, 0x9c, 0xe5, 0x6b, 0x7d, 0xfe, 0x07, 0xcc, 0x72, 0x6c, 0xf8, 0x45, 0x01, 0x8b, 0xa3, 0x1e, + 0x85, 0x86, 0xa4, 0xea, 0x75, 0x6e, 0x57, 0x1f, 0x4c, 0x9e, 0x10, 0x9f, 0x8c, 0xb6, 0xf5, 0xe1, + 0xdb, 0xef, 0xd3, 0xa9, 0x0d, 0xb8, 0x1e, 0x2f, 0x18, 0xab, 0x4f, 0xac, 0x74, 0xc9, 0xd0, 0x51, + 0x9e, 0x8f, 0x0a, 0x00, 0x57, 0x2e, 0x86, 0x9b, 0x45, 0xdd, 0xc6, 0x76, 0x80, 0x7a, 0x6f, 0x92, + 0x50, 0x81, 0xb4, 0xc1, 0x91, 0xea, 0x70, 0x55, 0x82, 0x74, 0xe5, 0x7b, 0x78, 0xaa, 0x80, 0x4a, + 0xd6, 0xaa, 0x70, 0xab, 0xa8, 0x87, 0x64, 0x33, 0xa8, 0xf7, 0x27, 0x0b, 0x16, 0x48, 0x4d, 0x8e, + 0xa4, 0xc1, 0x86, 0x04, 0x29, 0xb7, 0x16, 0x38, 0x55, 0xd6, 0xe2, 0xc5, 0x54, 0x92, 0x25, 0x51, + 0x4c, 0x25, 0xdb, 0x1a, 0xd7, 0x52, 0xe5, 0xd6, 0x09, 0xfc, 0xa4, 0x80, 0x85, 0x9c, 0x49, 0x61, + 0x71, 0x27, 0x89, 0xd1, 0xd5, 0xed, 0x09, 0xa3, 0x05, 0xd8, 0x26, 0x07, 0x5b, 0x87, 0x6b, 0x32, + 0xb0, 0xdc, 0x4a, 0xe0, 0x64, 0x39, 0xcf, 0x16, 0x93, 0xc9, 0x8c, 0x5f, 0x4c, 0x26, 0x5d, 0x04, + 0xd7, 0x92, 0xe5, 0x8d, 0xdd, 0xde, 0x3d, 0xbb, 0xa8, 0x29, 0xe7, 0x17, 0x35, 0xe5, 0xd7, 0x45, + 0x4d, 0x39, 0xb9, 0xac, 0x95, 0xce, 0x2f, 0x6b, 0xa5, 0xef, 0x97, 0xb5, 0xd2, 0x9b, 0xbb, 0x8e, + 0xcb, 0xba, 0xa1, 0xa5, 0x1f, 0x90, 0x81, 0x31, 0x74, 0xd9, 0x7b, 0x97, 0xc5, 0xd5, 0xb6, 0x6d, + 0xb4, 0x3d, 0x20, 0x76, 0xd8, 0xc7, 0x06, 0x3b, 0xf6, 0x31, 0xb5, 0xe6, 0xf8, 0x62, 0x79, 0xf8, + 0x27, 0x00, 0x00, 0xff, 0xff, 0x10, 0x40, 0xa2, 0x74, 0x6b, 0x08, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -2075,7 +2075,7 @@ func (m *QueryProvenHeightResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.ProvenHeight |= int64(b&0x7F) << shift + m.ProvenHeight |= uint64(b&0x7F) << shift if b < 0x80 { break } From 95207e8c421ece7efef778aaa1d8b2c8d729738a Mon Sep 17 00:00:00 2001 From: saiteja Date: Tue, 3 Sep 2024 11:44:59 +0530 Subject: [PATCH 30/58] feat: vote extensions --- keeper/keeper.go | 2 +- proto/sdk/avail/v1beta1/vote_extensions.proto | 13 + types/vote_extensions.pb.go | 365 ++++++++++++++++++ 3 files changed, 379 insertions(+), 1 deletion(-) create mode 100644 proto/sdk/avail/v1beta1/vote_extensions.proto create mode 100644 types/vote_extensions.pb.go diff --git a/keeper/keeper.go b/keeper/keeper.go index 32623e5..1543ebc 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -171,7 +171,7 @@ func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatu newStatus := READY_STATE if !req.IsSuccess { - newStatus = PENDING_STATE + newStatus = READY_STATE } else { UpdateProvenHeight(ctx, store, endHeight) } diff --git a/proto/sdk/avail/v1beta1/vote_extensions.proto b/proto/sdk/avail/v1beta1/vote_extensions.proto new file mode 100644 index 0000000..472ccf7 --- /dev/null +++ b/proto/sdk/avail/v1beta1/vote_extensions.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; +package sdk.avail.v1beta1; + +import "sdk/avail/v1beta1/tx.proto"; + +option go_package = "github.com/vitwit/avail-da-module/types"; + +// AvailVoteExtension +message AvailVoteExtension { + + int64 avail_height = 1; + Range range = 2; +} \ No newline at end of file diff --git a/types/vote_extensions.pb.go b/types/vote_extensions.pb.go new file mode 100644 index 0000000..9a98901 --- /dev/null +++ b/types/vote_extensions.pb.go @@ -0,0 +1,365 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: sdk/avail/v1beta1/vote_extensions.proto + +package types + +import ( + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + 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 + +// AvailVoteExtension +type AvailVoteExtension struct { + AvailHeight int64 `protobuf:"varint,1,opt,name=avail_height,json=availHeight,proto3" json:"avail_height,omitempty"` + Range *Range `protobuf:"bytes,2,opt,name=range,proto3" json:"range,omitempty"` +} + +func (m *AvailVoteExtension) Reset() { *m = AvailVoteExtension{} } +func (m *AvailVoteExtension) String() string { return proto.CompactTextString(m) } +func (*AvailVoteExtension) ProtoMessage() {} +func (*AvailVoteExtension) Descriptor() ([]byte, []int) { + return fileDescriptor_007bc07f2f11afa0, []int{0} +} +func (m *AvailVoteExtension) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *AvailVoteExtension) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_AvailVoteExtension.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 *AvailVoteExtension) XXX_Merge(src proto.Message) { + xxx_messageInfo_AvailVoteExtension.Merge(m, src) +} +func (m *AvailVoteExtension) XXX_Size() int { + return m.Size() +} +func (m *AvailVoteExtension) XXX_DiscardUnknown() { + xxx_messageInfo_AvailVoteExtension.DiscardUnknown(m) +} + +var xxx_messageInfo_AvailVoteExtension proto.InternalMessageInfo + +func (m *AvailVoteExtension) GetAvailHeight() int64 { + if m != nil { + return m.AvailHeight + } + return 0 +} + +func (m *AvailVoteExtension) GetRange() *Range { + if m != nil { + return m.Range + } + return nil +} + +func init() { + proto.RegisterType((*AvailVoteExtension)(nil), "sdk.avail.v1beta1.AvailVoteExtension") +} + +func init() { + proto.RegisterFile("sdk/avail/v1beta1/vote_extensions.proto", fileDescriptor_007bc07f2f11afa0) +} + +var fileDescriptor_007bc07f2f11afa0 = []byte{ + // 221 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2f, 0x4e, 0xc9, 0xd6, + 0x4f, 0x2c, 0x4b, 0xcc, 0xcc, 0xd1, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x2f, 0xcb, + 0x2f, 0x49, 0x8d, 0x4f, 0xad, 0x28, 0x49, 0xcd, 0x2b, 0xce, 0xcc, 0xcf, 0x2b, 0xd6, 0x2b, 0x28, + 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x2c, 0x4e, 0xc9, 0xd6, 0x03, 0x2b, 0xd4, 0x83, 0x2a, 0x94, 0x92, + 0xc2, 0xd4, 0x5b, 0x52, 0x01, 0x51, 0xae, 0x94, 0xce, 0x25, 0xe4, 0x08, 0x92, 0x09, 0xcb, 0x2f, + 0x49, 0x75, 0x85, 0x99, 0x25, 0xa4, 0xc8, 0xc5, 0x03, 0x56, 0x1f, 0x9f, 0x91, 0x9a, 0x99, 0x9e, + 0x51, 0x22, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x1c, 0xc4, 0x0d, 0x16, 0xf3, 0x00, 0x0b, 0x09, 0xe9, + 0x71, 0xb1, 0x16, 0x25, 0xe6, 0xa5, 0xa7, 0x4a, 0x30, 0x29, 0x30, 0x6a, 0x70, 0x1b, 0x49, 0xe8, + 0x61, 0xd8, 0xab, 0x17, 0x04, 0x92, 0x0f, 0x82, 0x28, 0x73, 0x72, 0x3c, 0xf1, 0x48, 0x8e, 0xf1, + 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, + 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xf5, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, + 0x5c, 0xfd, 0xb2, 0xcc, 0x92, 0xf2, 0xcc, 0x12, 0x88, 0x63, 0x75, 0x53, 0x12, 0x75, 0x73, 0xf3, + 0x53, 0x4a, 0x73, 0x52, 0xf5, 0x4b, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0x4e, 0x36, 0x06, + 0x04, 0x00, 0x00, 0xff, 0xff, 0x54, 0x29, 0xaf, 0xb7, 0x0c, 0x01, 0x00, 0x00, +} + +func (m *AvailVoteExtension) 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 *AvailVoteExtension) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AvailVoteExtension) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Range != nil { + { + size, err := m.Range.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintVoteExtensions(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.AvailHeight != 0 { + i = encodeVarintVoteExtensions(dAtA, i, uint64(m.AvailHeight)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintVoteExtensions(dAtA []byte, offset int, v uint64) int { + offset -= sovVoteExtensions(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *AvailVoteExtension) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.AvailHeight != 0 { + n += 1 + sovVoteExtensions(uint64(m.AvailHeight)) + } + if m.Range != nil { + l = m.Range.Size() + n += 1 + l + sovVoteExtensions(uint64(l)) + } + return n +} + +func sovVoteExtensions(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozVoteExtensions(x uint64) (n int) { + return sovVoteExtensions(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *AvailVoteExtension) 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 ErrIntOverflowVoteExtensions + } + 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: AvailVoteExtension: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AvailVoteExtension: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AvailHeight", wireType) + } + m.AvailHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowVoteExtensions + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.AvailHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Range", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowVoteExtensions + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthVoteExtensions + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthVoteExtensions + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Range == nil { + m.Range = &Range{} + } + if err := m.Range.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipVoteExtensions(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthVoteExtensions + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipVoteExtensions(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, ErrIntOverflowVoteExtensions + } + 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, ErrIntOverflowVoteExtensions + } + 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, ErrIntOverflowVoteExtensions + } + 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, ErrInvalidLengthVoteExtensions + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupVoteExtensions + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthVoteExtensions + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthVoteExtensions = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowVoteExtensions = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupVoteExtensions = fmt.Errorf("proto: unexpected end of group") +) From 0009f0e5b884f4cc8394a8625f8dc944c33ccc25 Mon Sep 17 00:00:00 2001 From: saiteja Date: Tue, 3 Sep 2024 12:41:43 +0530 Subject: [PATCH 31/58] refactor core lgic --- keeper/keeper.go | 57 +++++------------------------------------ keeper/store.go | 58 ++++++++++++++++++++++++++---------------- keys.go | 4 ++- relayer/publish.go | 4 +++ relayer/submit_data.go | 8 +++--- 5 files changed, 53 insertions(+), 78 deletions(-) diff --git a/keeper/keeper.go b/keeper/keeper.go index 1543ebc..87af593 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -91,62 +91,20 @@ func (k *Keeper) SetRelayer(r *relayer.Relayer) { k.relayer = r } -func (k *Keeper) SetBlobStatusPending(ctx sdk.Context, provenHeight, endHeight uint64) error { +func (k *Keeper) SetBlobStatusPending(ctx sdk.Context, startHeight, endHeight uint64) error { store := ctx.KVStore(k.storeKey) - if !IsStateReady(store) { //TOodo: we should check for expiration too + if !CanUpdateStatusToPending(store) { //TOodo: we should check for expiration too return errors.New("a block range with same start height is already being processed") } UpdateBlobStatus(ctx, store, PENDING_STATE) + UpdateStartHeight(ctx, store, startHeight) UpdateEndHeight(ctx, store, endHeight) return nil } -func (k *Keeper) SetBlobStatusSuccess(ctx sdk.Context, provenHeight, endHeight uint64) error { - - store := ctx.KVStore(k.storeKey) - - if !IsStateReady(store) { //TOodo: we should check for expiration too - return errors.New("a block range with same start height is already being processed") - } - - UpdateBlobStatus(ctx, store, READY_STATE) - UpdateEndHeight(ctx, store, endHeight) - return nil -} - -func (k *Keeper) GetProvenHeightFromStore(ctx sdk.Context) uint64 { - store := ctx.KVStore(k.storeKey) - heightBytes := store.Get(availblob1.ProvenHeightKey) - if heightBytes == nil || len(heightBytes) == 0 { - return 0 - } - - fmt.Println("heightt buyessssssss from......", heightBytes) - - provenHeight := binary.BigEndian.Uint64(heightBytes) - fmt.Println("proven height here............", provenHeight) - return provenHeight -} - -func (k *Keeper) GetEndHeightFromStore(ctx sdk.Context) uint64 { - store := ctx.KVStore(k.storeKey) - heightBytes := store.Get(availblob1.NextHeightKey) - - fmt.Println("heightBytes getEnd........", heightBytes) - if heightBytes == nil || len(heightBytes) == 0 { - return 0 - } - - fmt.Println("heightt buyessssssss from......", heightBytes) - - nextHeight := binary.BigEndian.Uint64(heightBytes) - fmt.Println("proven height here............", nextHeight) - return nextHeight -} - // Todo: remove this method later func (k *Keeper) SubmitBlob(ctx sdk.Context, req *types.MsgSubmitBlobRequest) (*types.MsgSubmitBlobResponse, error) { @@ -171,7 +129,7 @@ func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatu newStatus := READY_STATE if !req.IsSuccess { - newStatus = READY_STATE + newStatus = FAILURE_STATE } else { UpdateProvenHeight(ctx, store, endHeight) } @@ -200,14 +158,11 @@ func (k *Keeper) CheckHeight(endHeight uint64) error { func (k *Keeper) SubmitBlobStatus(ctx sdk.Context, _ *types.QuerySubmitBlobStatusRequest) (*types.QuerySubmitBlobStatusResponse, error) { // Todo: implement query store := ctx.KVStore(k.storeKey) - provenHeight := k.GetProvenHeightFromStore(ctx) + startHeight := k.GetStartHeightFromStore(ctx) endHeight := k.GetEndHeightFromStore(ctx) status := GetStatusFromStore(store) statusString := ParseStatus(status) - startHeight := provenHeight + 1 - if provenHeight == 0 { - startHeight = 0 - } + return &types.QuerySubmitBlobStatusResponse{ Range: &types.Range{From: startHeight, To: endHeight}, Status: statusString, diff --git a/keeper/store.go b/keeper/store.go index 604e22c..cc1d34c 100644 --- a/keeper/store.go +++ b/keeper/store.go @@ -2,12 +2,11 @@ package keeper import ( "encoding/binary" - "fmt" + "cosmossdk.io/collections" storetypes2 "cosmossdk.io/store/types" sdk "github.com/cosmos/cosmos-sdk/types" availblob1 "github.com/vitwit/avail-da-module" - "github.com/vitwit/avail-da-module/types" ) const ( @@ -32,26 +31,15 @@ func ParseStatus(status uint32) string { } } -func IsAlreadyExist(ctx sdk.Context, store storetypes2.KVStore, blocksRange types.Range) bool { - pendingBlobStoreKey := availblob1.PendingBlobsStoreKey(blocksRange) - blobStatus := store.Get(pendingBlobStoreKey) - fmt.Println("blob status:", blobStatus, blobStatus == nil) - if blobStatus == nil { - return false - } - return true -} - -func IsStateReady(store storetypes2.KVStore) bool { +func CanUpdateStatusToPending(store storetypes2.KVStore) bool { statusBytes := store.Get(availblob1.BlobStatusKey) - fmt.Println("status bytes............", statusBytes) if statusBytes == nil || len(statusBytes) == 0 { return true } status := binary.BigEndian.Uint32(statusBytes) - return status == READY_STATE + return status == READY_STATE || status == FAILURE_STATE } func GetStatusFromStore(store storetypes2.KVStore) uint32 { @@ -76,22 +64,48 @@ func UpdateBlobStatus(ctx sdk.Context, store storetypes2.KVStore, status uint32) return nil } +func UpdateStartHeight(ctx sdk.Context, store storetypes2.KVStore, startHeight uint64) error { + return updateHeight(store, availblob1.PrevHeightKey, startHeight) +} + func UpdateEndHeight(ctx sdk.Context, store storetypes2.KVStore, endHeight uint64) error { + return updateHeight(store, availblob1.NextHeightKey, endHeight) +} + +func UpdateProvenHeight(ctx sdk.Context, store storetypes2.KVStore, provenHeight uint64) error { + return updateHeight(store, availblob1.ProvenHeightKey, provenHeight) +} +func updateHeight(store storetypes2.KVStore, key collections.Prefix, height uint64) error { heightBytes := make([]byte, 8) - binary.BigEndian.PutUint64(heightBytes, endHeight) + binary.BigEndian.PutUint64(heightBytes, height) - store.Set(availblob1.NextHeightKey, heightBytes) + store.Set(key, heightBytes) return nil } -func UpdateProvenHeight(ctx sdk.Context, store storetypes2.KVStore, endHeight uint64) error { +func (k *Keeper) GetProvenHeightFromStore(ctx sdk.Context) uint64 { + return k.getHeight(ctx, availblob1.ProvenHeightKey) +} - heightBytes := make([]byte, 8) +func (k *Keeper) GetStartHeightFromStore(ctx sdk.Context) uint64 { + return k.getHeight(ctx, availblob1.PrevHeightKey) +} - binary.BigEndian.PutUint64(heightBytes, endHeight) +func (k *Keeper) GetEndHeightFromStore(ctx sdk.Context) uint64 { - store.Set(availblob1.ProvenHeightKey, heightBytes) - return nil + return k.getHeight(ctx, availblob1.NextHeightKey) +} + +func (k *Keeper) getHeight(ctx sdk.Context, key collections.Prefix) uint64 { + store := ctx.KVStore(k.storeKey) + heightBytes := store.Get(key) + + if heightBytes == nil || len(heightBytes) == 0 { + return 0 + } + + height := binary.BigEndian.Uint64(heightBytes) + return height } diff --git a/keys.go b/keys.go index 90e5e5a..6e8edfb 100644 --- a/keys.go +++ b/keys.go @@ -31,7 +31,9 @@ var ( BlobStatusKey = collections.NewPrefix(6) - NextHeightKey = collections.NewPrefix(7) + PrevHeightKey = collections.NewPrefix(7) + + NextHeightKey = collections.NewPrefix(8) ) const ( diff --git a/relayer/publish.go b/relayer/publish.go index f741d20..c88b87e 100644 --- a/relayer/publish.go +++ b/relayer/publish.go @@ -93,7 +93,11 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo bb = append(bb, blockBz...) } + fmt.Println("is it coming here where we post to DA") + blockInfo, err := r.SubmitDataToClient(r.rpcClient.config.Seed, r.rpcClient.config.AppID, bb, blocks, r.rpcClient.config.LightClientURL) + + fmt.Println("after submission.............", err) if err != nil { r.logger.Error("Error while submitting block(s) to Avail DA", "height_start", blocks[0], diff --git a/relayer/submit_data.go b/relayer/submit_data.go index 11f9986..94f05df 100644 --- a/relayer/submit_data.go +++ b/relayer/submit_data.go @@ -19,11 +19,11 @@ import ( func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks []int64, lightClientUrl string) (BlockInfo, error) { fmt.Println("calling twiceeeee.........", blocks) var blockInfo BlockInfo - if r.submittedBlocksCache[blocks[0]] { - return blockInfo, nil - } + // if r.submittedBlocksCache[blocks[0]] { + // return blockInfo, nil + // } - r.submittedBlocksCache[blocks[0]] = true + // r.submittedBlocksCache[blocks[0]] = true delete(r.submittedBlocksCache, blocks[0]-int64(len(blocks))) handler := NewHTTPClientHandler() From 4912fa508db3e861503a72fb2aca97397bfeaf02 Mon Sep 17 00:00:00 2001 From: saiteja Date: Wed, 4 Sep 2024 16:51:23 +0530 Subject: [PATCH 32/58] feat: enable vote extensions --- simapp/app/app.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/simapp/app/app.go b/simapp/app/app.go index b4e49a2..e3e7800 100644 --- a/simapp/app/app.go +++ b/simapp/app/app.go @@ -709,10 +709,22 @@ func NewChainApp( // must be done after relayer is created app.AvailBlobKeeper.SetRelayer(app.Availblobrelayer) + voteExtensionHandler := availblobkeeper.NewVoteExtHandler( + logger, + app.AvailBlobKeeper, + ) + dph := baseapp.NewDefaultProposalHandler(bApp.Mempool(), bApp) - availBlobProposalHandler := availblobkeeper.NewProofOfBlobProposalHandler(app.AvailBlobKeeper, dph.PrepareProposalHandler(), dph.ProcessProposalHandler()) + availBlobProposalHandler := availblobkeeper.NewProofOfBlobProposalHandler( + app.AvailBlobKeeper, + dph.PrepareProposalHandler(), + dph.ProcessProposalHandler(), + *voteExtensionHandler, + ) bApp.SetPrepareProposal(availBlobProposalHandler.PrepareProposal) bApp.SetProcessProposal(availBlobProposalHandler.ProcessProposal) + app.SetExtendVoteHandler(voteExtensionHandler.ExtendVoteHandler()) + app.SetVerifyVoteExtensionHandler(voteExtensionHandler.VerifyVoteExtensionHandler()) // --- Module Options --- From 1ecc9f1114d3f6fc9559dc336afb06cf4e570ee3 Mon Sep 17 00:00:00 2001 From: saiteja Date: Wed, 4 Sep 2024 16:51:32 +0530 Subject: [PATCH 33/58] feat: enable vote extensions --- keeper/abci.go | 92 ++++++++++++++++++++++++++++++++++++++-- keeper/vote_entension.go | 70 ++++++++++++++++++++++++++++++ 2 files changed, 159 insertions(+), 3 deletions(-) create mode 100644 keeper/vote_entension.go diff --git a/keeper/abci.go b/keeper/abci.go index a9b907a..b1271da 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -2,44 +2,91 @@ package keeper import ( "bytes" + "encoding/json" + "errors" "fmt" abci "github.com/cometbft/cometbft/abci/types" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/vitwit/avail-da-module/types" ) +type StakeWeightedVotes struct { + Votes map[types.Range]int64 + ExtendedCommitInfo abci.ExtendedCommitInfo +} + type ProofOfBlobProposalHandler struct { keeper *Keeper prepareProposalHandler sdk.PrepareProposalHandler processProposalHandler sdk.ProcessProposalHandler + voteExtHandler VoteExtHandler } func NewProofOfBlobProposalHandler( k *Keeper, prepareProposalHandler sdk.PrepareProposalHandler, processProposalHandler sdk.ProcessProposalHandler, + voteExtHandler VoteExtHandler, ) *ProofOfBlobProposalHandler { return &ProofOfBlobProposalHandler{ keeper: k, prepareProposalHandler: prepareProposalHandler, processProposalHandler: processProposalHandler, + voteExtHandler: voteExtHandler, } } func (h *ProofOfBlobProposalHandler) PrepareProposal(ctx sdk.Context, req *abci.RequestPrepareProposal) (*abci.ResponsePrepareProposal, error) { h.keeper.proposerAddress = req.ProposerAddress + proposalTxs := req.Txs + + // h.voteExtHandler.ExtendVoteHandler()(nil,err) + + // resp, err := h.prepareProposalHandler(ctx, req) + // if err != nil { + // return nil, err + // } - resp, err := h.prepareProposalHandler(ctx, req) + votes, err := h.aggregateVotes(ctx, req.LocalLastCommit) if err != nil { + fmt.Println("error while aggregating votes", err) return nil, err } - return resp, nil + injectedVoteExtTx := StakeWeightedVotes{ + Votes: votes, + ExtendedCommitInfo: req.LocalLastCommit, + } + + bz, err := json.Marshal(injectedVoteExtTx) + if err != nil { + fmt.Println("failed to encode injected vote extension tx", "err", err) + return nil, errors.New("failed to encode injected vote extension tx") + } + + proposalTxs = append(proposalTxs, bz) + return &abci.ResponsePrepareProposal{ + Txs: proposalTxs, + }, nil } func (h *ProofOfBlobProposalHandler) ProcessProposal(ctx sdk.Context, req *abci.RequestProcessProposal) (*abci.ResponseProcessProposal, error) { - return h.processProposalHandler(ctx, req) + if len(req.Txs) == 0 { + return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil + } + + var injectedVoteExtTx StakeWeightedVotes + if err := json.Unmarshal(req.Txs[0], &injectedVoteExtTx); err != nil { + fmt.Println("failed to decode injected vote extension tx", "err", err) + return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil + } + + fmt.Println("injected data is:..............", injectedVoteExtTx) + return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil + } func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { @@ -103,3 +150,42 @@ func (k *Keeper) IsValidBlockToPostTODA(height uint64) bool { return true } + +func (h *ProofOfBlobProposalHandler) aggregateVotes(ctx sdk.Context, ci abci.ExtendedCommitInfo) (map[types.Range]int64, error) { + from := h.keeper.GetStartHeightFromStore(ctx) + to := h.keeper.GetEndHeightFromStore(ctx) + + pendingBlockRange := types.Range{ + From: from, + To: to, + } + + votes := make(map[types.Range]int64, 1) + + var totalStake int64 + + for _, v := range ci.Votes { + // TODO: why?? + if v.BlockIdFlag != cmtproto.BlockIDFlagCommit { + continue + } + + var voteExt VoteExtension + if err := json.Unmarshal(v.VoteExtension, &voteExt); err != nil { + h.voteExtHandler.logger.Error("failed to decode vote extension", "err", err, "validator", fmt.Sprintf("%x", v.Validator.Address)) + return nil, err + } + + totalStake += v.Validator.Power + + for voteRange, isVoted := range voteExt.Votes { + if voteRange != pendingBlockRange || !isVoted { + continue + } + + votes[voteRange] += v.Validator.Power + } + + } + return votes, nil +} diff --git a/keeper/vote_entension.go b/keeper/vote_entension.go new file mode 100644 index 0000000..b31d49a --- /dev/null +++ b/keeper/vote_entension.go @@ -0,0 +1,70 @@ +package keeper + +import ( + "encoding/json" + "fmt" + + "cosmossdk.io/log" + abci "github.com/cometbft/cometbft/abci/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/vitwit/avail-da-module/types" +) + +type VoteExtHandler struct { + logger log.Logger + + Keeper *Keeper +} + +// TODO: add required parameters like avail light client url, etc.. +func NewVoteExtHandler( + logger log.Logger, + keeper *Keeper, +) *VoteExtHandler { + return &VoteExtHandler{ + logger: logger, + Keeper: keeper, + } +} + +// TODO: change the Vote Extension to be actually usable +type VoteExtension struct { + Votes map[types.Range]bool +} + +func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { + return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { + + fmt.Println("coming to extend vote handler.........") + // TODO: implement proper logic, this is for demo purpose only + from := h.Keeper.GetStartHeightFromStore(ctx) + end := h.Keeper.GetEndHeightFromStore(ctx) + + pendingRange := types.Range{ + From: from, + To: end, + } + + var Votes map[types.Range]bool + Votes[pendingRange] = true + voteExt := VoteExtension{ + Votes: Votes, + } + + //TODO: use proto marshalling instead + votesBytes, err := json.Marshal(voteExt) + if err != nil { + return nil, fmt.Errorf("failed to marshal vote extension: %w", err) + } + return &abci.ResponseExtendVote{ + VoteExtension: votesBytes, + }, nil + } +} + +func (h *VoteExtHandler) VerifyVoteExtensionHandler() sdk.VerifyVoteExtensionHandler { + return func(ctx sdk.Context, req *abci.RequestVerifyVoteExtension) (*abci.ResponseVerifyVoteExtension, error) { + // TODO: write proper validation for the votes + return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_ACCEPT}, nil + } +} From 4b25aae1625a7f9442864230bfa97cf3cf6937aa Mon Sep 17 00:00:00 2001 From: saiteja Date: Wed, 4 Sep 2024 18:11:11 +0530 Subject: [PATCH 34/58] feat: fix vote extensions bug --- simapp/app/app.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/simapp/app/app.go b/simapp/app/app.go index e3e7800..0291ab3 100644 --- a/simapp/app/app.go +++ b/simapp/app/app.go @@ -723,8 +723,8 @@ func NewChainApp( ) bApp.SetPrepareProposal(availBlobProposalHandler.PrepareProposal) bApp.SetProcessProposal(availBlobProposalHandler.ProcessProposal) - app.SetExtendVoteHandler(voteExtensionHandler.ExtendVoteHandler()) - app.SetVerifyVoteExtensionHandler(voteExtensionHandler.VerifyVoteExtensionHandler()) + bApp.SetExtendVoteHandler(voteExtensionHandler.ExtendVoteHandler()) + bApp.SetVerifyVoteExtensionHandler(voteExtensionHandler.VerifyVoteExtensionHandler()) // --- Module Options --- From 1c75bf6b250a3beae98cfb5036c5adbcf08fd857 Mon Sep 17 00:00:00 2001 From: saiteja Date: Wed, 4 Sep 2024 18:11:24 +0530 Subject: [PATCH 35/58] feat: fix vote extensions bug --- keeper/abci.go | 30 +++++++++++++----------------- keeper/submitBlobTx.go | 2 +- keeper/vote_entension.go | 26 ++++++++++++++++++-------- 3 files changed, 32 insertions(+), 26 deletions(-) diff --git a/keeper/abci.go b/keeper/abci.go index b1271da..195c507 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -3,17 +3,15 @@ package keeper import ( "bytes" "encoding/json" - "errors" "fmt" abci "github.com/cometbft/cometbft/abci/types" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/vitwit/avail-da-module/types" ) type StakeWeightedVotes struct { - Votes map[types.Range]int64 + Votes map[string]int64 ExtendedCommitInfo abci.ExtendedCommitInfo } @@ -22,7 +20,7 @@ type ProofOfBlobProposalHandler struct { prepareProposalHandler sdk.PrepareProposalHandler processProposalHandler sdk.ProcessProposalHandler - voteExtHandler VoteExtHandler + VoteExtHandler VoteExtHandler } func NewProofOfBlobProposalHandler( @@ -35,7 +33,7 @@ func NewProofOfBlobProposalHandler( keeper: k, prepareProposalHandler: prepareProposalHandler, processProposalHandler: processProposalHandler, - voteExtHandler: voteExtHandler, + VoteExtHandler: voteExtHandler, } } @@ -61,10 +59,12 @@ func (h *ProofOfBlobProposalHandler) PrepareProposal(ctx sdk.Context, req *abci. ExtendedCommitInfo: req.LocalLastCommit, } + fmt.Println("votes..................", votes, injectedVoteExtTx) + bz, err := json.Marshal(injectedVoteExtTx) if err != nil { fmt.Println("failed to encode injected vote extension tx", "err", err) - return nil, errors.New("failed to encode injected vote extension tx") + // return nil, errors.New("failed to encode injected vote extension tx") } proposalTxs = append(proposalTxs, bz) @@ -81,7 +81,7 @@ func (h *ProofOfBlobProposalHandler) ProcessProposal(ctx sdk.Context, req *abci. var injectedVoteExtTx StakeWeightedVotes if err := json.Unmarshal(req.Txs[0], &injectedVoteExtTx); err != nil { fmt.Println("failed to decode injected vote extension tx", "err", err) - return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil + // return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } fmt.Println("injected data is:..............", injectedVoteExtTx) @@ -151,16 +151,12 @@ func (k *Keeper) IsValidBlockToPostTODA(height uint64) bool { return true } -func (h *ProofOfBlobProposalHandler) aggregateVotes(ctx sdk.Context, ci abci.ExtendedCommitInfo) (map[types.Range]int64, error) { +func (h *ProofOfBlobProposalHandler) aggregateVotes(ctx sdk.Context, ci abci.ExtendedCommitInfo) (map[string]int64, error) { from := h.keeper.GetStartHeightFromStore(ctx) to := h.keeper.GetEndHeightFromStore(ctx) - pendingBlockRange := types.Range{ - From: from, - To: to, - } - - votes := make(map[types.Range]int64, 1) + pendingRangeKey := Key(from, to) + votes := make(map[string]int64, 1) var totalStake int64 @@ -172,14 +168,14 @@ func (h *ProofOfBlobProposalHandler) aggregateVotes(ctx sdk.Context, ci abci.Ext var voteExt VoteExtension if err := json.Unmarshal(v.VoteExtension, &voteExt); err != nil { - h.voteExtHandler.logger.Error("failed to decode vote extension", "err", err, "validator", fmt.Sprintf("%x", v.Validator.Address)) - return nil, err + h.VoteExtHandler.logger.Error("failed to decode vote extension", "err", err, "validator", fmt.Sprintf("%x", v.Validator.Address)) + //return nil, err } totalStake += v.Validator.Power for voteRange, isVoted := range voteExt.Votes { - if voteRange != pendingBlockRange || !isVoted { + if voteRange != pendingRangeKey || !isVoted { continue } diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go index 5a3cd5d..76158a4 100644 --- a/keeper/submitBlobTx.go +++ b/keeper/submitBlobTx.go @@ -13,7 +13,7 @@ import ( func (k Keeper) SubmitBlobTx2(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { cdc := k.cdc - homepath := "/home/vitwit/.availsdk/keyring-test" + homepath := "/home/vitwit/.availsdk" cc, err := dacli.CreateChainClient(sdk.KeyringServiceName(), ctx.ChainID(), homepath, cdc.(codec.Codec)) if err != nil { diff --git a/keeper/vote_entension.go b/keeper/vote_entension.go index b31d49a..90adedc 100644 --- a/keeper/vote_entension.go +++ b/keeper/vote_entension.go @@ -7,7 +7,6 @@ import ( "cosmossdk.io/log" abci "github.com/cometbft/cometbft/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/vitwit/avail-da-module/types" ) type VoteExtHandler struct { @@ -27,12 +26,17 @@ func NewVoteExtHandler( } } +func Key(from, to uint64) string { + return fmt.Sprintln(from, " ", to) +} + // TODO: change the Vote Extension to be actually usable type VoteExtension struct { - Votes map[types.Range]bool + Votes map[string]bool } func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { + return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { fmt.Println("coming to extend vote handler.........") @@ -40,22 +44,28 @@ func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { from := h.Keeper.GetStartHeightFromStore(ctx) end := h.Keeper.GetEndHeightFromStore(ctx) - pendingRange := types.Range{ - From: from, - To: end, - } + pendingRangeKey := Key(from, end) - var Votes map[types.Range]bool - Votes[pendingRange] = true + Votes := make(map[string]bool, 1) + Votes[pendingRangeKey] = true voteExt := VoteExtension{ Votes: Votes, } + fmt.Println("before marshalling....", voteExt) + //TODO: use proto marshalling instead votesBytes, err := json.Marshal(voteExt) if err != nil { return nil, fmt.Errorf("failed to marshal vote extension: %w", err) } + + var AfterVoteExt VoteExtension + err = json.Unmarshal(votesBytes, &AfterVoteExt) + if err != nil { + fmt.Println("muurshalling error.......................") + } + return &abci.ResponseExtendVote{ VoteExtension: votesBytes, }, nil From 6a0c3988ba90a4d2b3f472c671d0c8ab794472a8 Mon Sep 17 00:00:00 2001 From: saiteja Date: Thu, 5 Sep 2024 10:52:32 +0530 Subject: [PATCH 36/58] fix: config script for vote extension height --- simapp/init-simapp.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/simapp/init-simapp.sh b/simapp/init-simapp.sh index 3a8767c..36ccbd1 100755 --- a/simapp/init-simapp.sh +++ b/simapp/init-simapp.sh @@ -6,6 +6,7 @@ BOB_MNEMONIC="remain then chuckle hockey protect sausage govern curve hobby aisl SAI_MNEMONIC="festival borrow upon ritual remind song execute chase toward fan neck subway canal throw nothing ticket frown leave thank become extend balcony strike fame" TEJA_MNEMONIC="claim infant gather cereal sentence general cheese float hero dwarf miracle oven tide virus question choice say relax similar rice surround deal smooth rival" UNKNOWN_MNOMONIC="purpose clutch ill track skate syrup cost among piano elegant close chaos come quit orchard acquire plunge hockey swift tongue salt supreme sting night" +DAEMON_HOME="/home/vitwit/.availsdk" if [ -z "$SIMD_BIN" ]; then echo "SIMD_BIN is not set. Make sure to run make install before"; exit 1; fi echo "using $SIMD_BIN" @@ -29,3 +30,5 @@ $SIMD_BIN genesis add-genesis-account unknown 5000000000stake --keyring-backend $SIMD_BIN genesis gentx alice 1000000stake --chain-id demo $SIMD_BIN genesis collect-gentxs + +sed -i "s/\"vote_extensions_enable_height\": \"0\"/\"vote_extensions_enable_height\": \"1\"/g" $DAEMON_HOME/config/genesis.json From 62bece9b7a0a0d125565a1638f5fbfb3c61540e2 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Thu, 5 Sep 2024 11:29:16 +0530 Subject: [PATCH 37/58] fix typo --- relayer/publish.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/relayer/publish.go b/relayer/publish.go index c88b87e..87ec3d8 100644 --- a/relayer/publish.go +++ b/relayer/publish.go @@ -148,7 +148,7 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo func ExecuteTX(ctx sdk.Context, msg types.MsgUpdateBlobStatusRequest, cdc codec.BinaryCodec) error { // Define keyring and RPC client configuration - homePath := "/home/vitwit/.simapp" + homePath := "/home/vitwit/.availsdk" keyName := "alice" rpcAddress := "http://localhost:26657" From 529337ad65c9fbc38131ab9c530d4ff48dbb0b1f Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Thu, 5 Sep 2024 13:04:20 +0530 Subject: [PATCH 38/58] fix client --- chainclient/broadcast_tx.go | 210 ++++++++++------------ chainclient/create_client.go | 175 ++++++++++++------ chainclient/import_accounts.go | 190 -------------------- keeper/abci.go | 3 +- keeper/client.go | 320 ++++++++++++++++----------------- keeper/submitBlobTx.go | 113 ------------ relayer/client.go | 27 --- relayer/publish.go | 189 ++++++++++--------- 8 files changed, 477 insertions(+), 750 deletions(-) delete mode 100644 chainclient/import_accounts.go delete mode 100644 keeper/submitBlobTx.go diff --git a/chainclient/broadcast_tx.go b/chainclient/broadcast_tx.go index 14e13d0..7360c1a 100644 --- a/chainclient/broadcast_tx.go +++ b/chainclient/broadcast_tx.go @@ -1,138 +1,116 @@ -package client +package chainclient import ( "fmt" + "log" + "os" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/spf13/pflag" + cometrpc "github.com/cometbft/cometbft/rpc/client/http" + clitx "github.com/cosmos/cosmos-sdk/client/tx" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/vitwit/avail-da-module/types" - // tmjson "github.com/tendermint/tendermint/libs/json" - sdk "github.com/cosmos/cosmos-sdk/types" -) + "path/filepath" -func (c *ChainClient) BroadcastTx(msg types.MsgSubmitBlobRequest, fromName string, fromAddr sdk.AccAddress) error { - fmt.Println("from name and from address.........", fromName, fromAddr) + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) - clientCtx, err := c.BuildClientCtx(fromName, fromAddr) +func GetBinPath() string { + homeDir, err := os.UserHomeDir() if err != nil { - return err + log.Fatal(err) } - flags := *pflag.NewFlagSet("my-flags", pflag.ContinueOnError) - fmt.Println("new flagssssss.......", flags) + availdHomePath := filepath.Join(homeDir, ".availsdk") + fmt.Println("availdHonmePath.......", availdHomePath) + return availdHomePath +} + +func ExecuteTX(ctx sdk.Context, msg types.MsgUpdateBlobStatusRequest, cdc codec.BinaryCodec) error { + // Define keyring and RPC client configuration + + // homePath := "/home/vitwit/.availsdk" + homePath := GetBinPath() + key := os.Getenv("KEY") + fmt.Println("get key namee.........", key) + if key == "" { //TODO : remove this later + key = "alice" + } + keyName := key + rpcAddress := "http://localhost:26657" - // err = clitx.GenerateOrBroadcastTxCLI(clientCtx, &flags, &msg) - txf, err := tx.NewFactoryCLI(clientCtx, &flags) - fmt.Println("here the eroor with txf....", txf, err) + // Create a keyring + kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, homePath, os.Stdin, cdc.(codec.Codec)) if err != nil { - return err + return fmt.Errorf("error creating keyring: %w", err) } - err = tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, &msg) + // List all keys in the keyring + // keys, err := kr.List() + // if err != nil { + // fmt.Println("error listing keys:", err) + // } + + info, err := kr.Key(keyName) + valAddr, err := info.GetAddress() + fmt.Println("after address................", valAddr) + + // valAddr, err := sdk.AccAddressFromBech32(addr.String()) + // fmt.Println("val addr, err..", valAddr, err, addr) + + // fmt.Println("keysss........", keys) + + // // Print out the keys + // for _, keyInfo := range keys { + // addr, err := keyInfo.GetAddress() + // fmt.Println("err..", err) + // fmt.Printf("Name: %s, Address: %s\n", keyInfo.Name, addr) + // } + + // Create an RPC client + rpcClient, err := cometrpc.NewWithTimeout(rpcAddress, "/websocket", 3) if err != nil { - fmt.Println("error insideeeeeeeeeeee............", err) - return err + return fmt.Errorf("error creating RPC client: %w", err) } - return nil -} + // Create a new client context + clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc, homePath, valAddr) -// BuildClientCtx builds the context for the client -func (c *ChainClient) BuildClientCtx(accountName string, accountAddress sdk.AccAddress) (client.Context, error) { - // info, err := c.clientCtx.Keyring.Key(accountName) + // Retrieve the validator address (replace with actual logic to get the address) + // valAddr, err = sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") // if err != nil { - // return client.Context{}, err + // return fmt.Errorf("error parsing validator address: %w", err) // } - return c.clientCtx. - WithFromName(accountName). - WithFromAddress(accountAddress), nil -} -// // PrepareBroadcast performs checks and operations before broadcasting messages -// func (c *ChainClient) PrepareBroadcast(msgs ...types.Msg) error { -// // validate msgs -// for _, msg := range msgs { -// if err := msg.ValidateBasic(); err != nil { -// return err -// } -// } - -// c.out.Reset() - -// return nil -// } - -// // SignTx signs tx and return tx bytes -// func (c *ChainClient) SignTx(fromName string, fromAddr types.AccAddress, clientCtx client.Context, msgs ...types.Msg) ([]byte, error) { -// clientCtx, err := c.BuildClientCtx(fromName, fromAddr) -// if err != nil { -// return []byte{}, err -// } - -// if err := c.PrepareBroadcast(msgs...); err != nil { -// return []byte{}, err -// } - -// flags := *pflag.NewFlagSet("my-flags", pflag.ContinueOnError) - -// txf, err := tx.NewFactoryCLI(clientCtx, &flags) -// if err != nil { -// return []byte{}, err -// } - -// unsignedTx, err := tx.BuildUnsignedTx(txf, msgs...) -// if err != nil { -// return []byte{}, err -// } - -// err = tx.Sign(txf, clientCtx.GetFromName(), unsignedTx, true) -// if err != nil { -// return []byte{}, err -// } -// return clientCtx.TxConfig.TxEncoder()(unsignedTx.GetTx()) -// } - -// // Broadcast directly broadcasts the messages -// func (c *ChainClient) Broadcast(fromName string, fromAddr types.AccAddress, clientCtx client.Context, msgs ...types.Msg) (*types.TxResponse, error) { -// clientCtx, err := c.BuildClientCtx(fromName, fromAddr) -// if err != nil { -// return &types.TxResponse{}, err -// } - -// if err := c.PrepareBroadcast(msgs...); err != nil { -// return &types.TxResponse{}, err -// } - -// // broadcast tx. -// if err := tx.BroadcastTx(clientCtx, c.factory, msgs...); err != nil { -// return &types.TxResponse{}, err -// } - -// // return c.handleBroadcastResult() -// return &types.TxResponse{}, nil -// } - -// // HandleBroadcastResult handles the result of broadcast messages result and checks if an error occurred -// // func (c *ChainClient) handleBroadcastResult() (*types.TxResponse, error) { -// // var out types.TxResponse -// // if err := tmjson.Unmarshal(c.out.Bytes(), &out); err != nil { -// // return &out, err -// // } -// // if out.Code > 0 { -// // return &out, fmt.Errorf("tx error with code '%d' code: %s", out.Code, out.RawLog) -// // } -// // return &out, nil -// // } - -// // BuildClientCtx builds the context for the client -// func (c *ChainClient) BuildClientCtx(accountName string, accountAddress types.AccAddress) (client.Context, error) { -// // info, err := c.clientCtx.Keyring.Key(accountName) -// // if err != nil { -// // return client.Context{}, err -// // } -// return c.clientCtx. -// WithFromName(accountName). -// WithFromAddress(accountAddress), nil -// } + // Set the client context's from fields + clientCtx.FromName = keyName + clientCtx.FromAddress = valAddr + + // Fetch account number and sequence from the blockchain + accountRetriever := authtypes.AccountRetriever{} + account, err := accountRetriever.GetAccount(clientCtx, valAddr) + if err != nil { + return fmt.Errorf("error retrieving account: %w", err) + } + + fmt.Println("account details......", account.GetAccountNumber(), account.GetSequence()) + + // Set the correct account number and sequence + factory := NewFactory(clientCtx). + WithAccountNumber(account.GetAccountNumber()). + WithSequence(account.GetSequence()) + + // Create a transaction factory and set the validator address in the message + // factory := NewFactory(clientCtx) + msg.ValidatorAddress = valAddr.String() + // time.Sleep(10 * time.Second) + + // Generate and broadcast the transaction + if err := clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg); err != nil { + return fmt.Errorf("error broadcasting transaction: %w", err) + } + + return nil +} diff --git a/chainclient/create_client.go b/chainclient/create_client.go index 61375e7..23addf6 100644 --- a/chainclient/create_client.go +++ b/chainclient/create_client.go @@ -1,86 +1,153 @@ -package client +package chainclient import ( - "bytes" "fmt" - "os" cometrpc "github.com/cometbft/cometbft/rpc/client/http" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/std" sdk "github.com/cosmos/cosmos-sdk/types" -) + "github.com/cosmos/cosmos-sdk/types/tx/signing" + authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/go-bip39" + + // "github.com/tendermint/starport/starport/pkg/xfilepath" -// "github.com/emerishq/demeris-backend-models/cns" + "github.com/cosmos/cosmos-sdk/types/module" +) const ( - StagingEnvKey = "staging" - AkashMnemonicKey = "AKASH_MNEMONIC" - CosmosMnemonicKey = "COSMOS_MNEMONIC" - TerraMnemonicKey = "TERRA_MNEMONIC" - OsmosisMnemonicKey = "OSMOSIS_MNEMONIC" + defaultGasAdjustment = 1.0 + defaultGasLimit = 300000 ) -func CreateChainClient(keyringServiceName, chainID, homePath string, codec codec.Codec) (*ChainClient, error) { - nodeAddress := "http://localhost:26657" - kr, err := keyring.New(keyringServiceName, KeyringBackendTest, homePath, os.Stdin, codec) - if err != nil { - return nil, err +// var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) + +func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, + cdc codec.BinaryCodec, homepath string, fromAddress sdk.AccAddress) client.Context { + encodingConfig := MakeEncodingConfig() + + broadcastMode := flags.BroadcastSync + + return client.Context{}. + WithCodec(cdc.(codec.Codec)). + WithChainID(chainID). + WithFromAddress(fromAddress). + WithFromName("testkey"). + WithKeyringDir(homepath). + WithBroadcastMode(broadcastMode). + WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). + WithKeyring(kr). + WithAccountRetriever(authtypes.AccountRetriever{}). + WithClient(c).WithInterfaceRegistry(encodingConfig.InterfaceRegistry). + WithSkipConfirmation(true) +} + +// NewFactory creates a new Factory. +func NewFactory(clientCtx client.Context) tx.Factory { + return tx.Factory{}. + WithChainID(clientCtx.ChainID). + WithKeybase(clientCtx.Keyring). + WithGas(defaultGasLimit). + WithGasAdjustment(defaultGasAdjustment). + WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). + WithAccountRetriever(clientCtx.AccountRetriever). + WithTxConfig(clientCtx.TxConfig) +} + +// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. +func MakeEncodingConfig(modules ...module.AppModuleBasic) EncodingConfig { + aminoCodec := codec.NewLegacyAmino() + interfaceRegistry := codectypes.NewInterfaceRegistry() + codec := codec.NewProtoCodec(interfaceRegistry) + txCfg := authTx.NewTxConfig(codec, authTx.DefaultSignModes) + + encCfg := EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Codec: codec, + TxConfig: txCfg, + Amino: aminoCodec, } - wsClient, err := cometrpc.New(nodeAddress, "/websocket") + mb := module.NewBasicManager(modules...) + + std.RegisterLegacyAminoCodec(encCfg.Amino) + std.RegisterInterfaces(encCfg.InterfaceRegistry) + mb.RegisterLegacyAminoCodec(encCfg.Amino) + mb.RegisterInterfaces(encCfg.InterfaceRegistry) + + return encCfg +} + +// EncodingConfig specifies the concrete encoding types to use for a given app. +// This is provided for compatibility between protobuf and amino implementations. +type EncodingConfig struct { + InterfaceRegistry codectypes.InterfaceRegistry + Codec codec.Codec + TxConfig client.TxConfig + Amino *codec.LegacyAmino +} + +// ImportMnemonic is to import existing account mnemonic in keyring +func ImportMnemonic(keyName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { + info, err := AccountCreate(keyName, mnemonic, hdPath, c) // return account also if err != nil { return nil, err } - out := &bytes.Buffer{} - - address := "cosmos1ux2hl3y42nz6vtdl8k7t7f05k9p3r2k62zfvtv" - clientCtx := NewClientCtx(kr, wsClient, chainID, codec, out, address).WithChainID(chainID).WithNodeURI(nodeAddress) - fmt.Println("client ctxxx.......", clientCtx.FromName, clientCtx.FromAddress) - - factory := NewFactory(clientCtx) - return &ChainClient{ - factory: factory, - clientCtx: clientCtx, - out: out, - }, nil + + return info, nil } -// GetClient is to create client and imports mnemonic and returns created chain client -func GetClient(chainID string, cc ChainClient, homePath string, codec codec.Codec) (c *ChainClient, err error) { - // get chain info - // info, err := LoadSingleChainInfo(env, chainName) - // if err != nil { - // return nil, err - // } +// AccountCreate creates an account by name and mnemonic (optional) in the keyring. +func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { + if mnemonic == "" { + entropySeed, err := bip39.NewEntropy(256) + if err != nil { + return nil, err + } + mnemonic, err = bip39.NewMnemonic(entropySeed) + if err != nil { + return nil, err + } + } - // initSDKConfig(info.NodeInfo.Bech32Config) - c, err = CreateChainClient(sdk.KeyringServiceName(), chainID, homePath, codec) + algos, _ := c.Keyring.SupportedAlgorithms() + algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algos) if err != nil { return nil, err } - // // mnemonic := cc.Mnemonic - // // if env == StagingEnvKey { - // // mnemonic = GetMnemonic(chainName) - // // } - - // // c.AddressPrefix = info.NodeInfo.Bech32Config.PrefixAccount - // // c.HDPath = info.DerivationPath - // // c.Enabled = info.Enabled - // // c.ChainName = info.ChainName - // c.Mnemonic = ALICE_MNEMONIC - // c.ChainName = chainID - // // if len(info.Denoms) != 0 { - // // c.Denom = info.Denoms[0].Name - // // } + path := hd.CreateHDPath(118, 0, 0).String() + // fmt.Println("pathhh......", path) - // fmt.Println("mnemonic and chain id....", c.Mnemonic, c.ChainName, c.Key) + // record, str, err := c.Keyring.NewMnemonic("test_key1", keyring.English, path, keyring.DefaultBIP39Passphrase, hd.Secp256k1) + // fmt.Println("recorddddd.......", err, str, record) - err = c.ImportMnemonic(c.Key, c.Mnemonic, c.HDPath) + // k, _, err = kb.NewMnemonic("test", English, types.FullFundraiserPath, DefaultBIP39Passphrase, hd.Secp256k1) + info, err := c.Keyring.NewAccount(accountName, mnemonic, keyring.DefaultBIP39Passphrase, path, algo) + fmt.Println("after creationnnn.........", info, err) if err != nil { return nil, err } + // pk, err := info.GetPubKey() + // if err != nil { + // return nil, err + // } + + // addr := sdk.AccAddress(pk.Address()) + // fmt.Println("address hereee...", addr) + + // aa, err := info.GetAddress() + // fmt.Println("here aa and err.......", aa, err) - return c, nil + // account := c.ToAccount(info) + // account.Mnemonic = mnemonic + return info, nil } diff --git a/chainclient/import_accounts.go b/chainclient/import_accounts.go deleted file mode 100644 index 123c730..0000000 --- a/chainclient/import_accounts.go +++ /dev/null @@ -1,190 +0,0 @@ -package client - -import ( - "bytes" - "fmt" - "io" - - cometrpc "github.com/cometbft/cometbft/rpc/client/http" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/std" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/tx/signing" - authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - staking "github.com/cosmos/cosmos-sdk/x/staking/types" - - // "github.com/tendermint/starport/starport/pkg/xfilepath" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/go-bip39" - // "github.com/tendermint/starport/starport/pkg/spn" -) - -// var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) - -const ( - KeyringBackendTest = "test" - ALICE_MNEMONIC = "" - // ALICE_MNEMONIC = "all soap kiwi cushion federal skirt tip shock exist tragic verify lunar shine rely torch please view future lizard garbage humble medal leisure mimic" -) - -// ChainClient is client to interact with SPN. -type ChainClient struct { - factory tx.Factory - clientCtx client.Context - out *bytes.Buffer - Address string `json:"address"` - AddressPrefix string `json:"account_address_prefix"` - RPC string `json:"rpc"` - Key string `json:"key"` - Mnemonic string `json:"mnemonic"` - KeyringServiceName string `json:"keyring_service_name"` - HDPath string `json:"hd_path"` - Enabled bool `json:"enabled"` - ChainName string `json:"chain_name"` - Denom string `json:"denom"` -} - -// ImportMnemonic is to import existing account mnemonic in keyring -func (c ChainClient) ImportMnemonic(keyName, mnemonic, hdPath string) (err error) { - err = c.AccountCreate(keyName, mnemonic, hdPath) // return account also - fmt.Println("here the accc details.......", keyName, mnemonic, hdPath) - if err != nil { - return err - } - - return nil -} - -// AccountCreate creates an account by name and mnemonic (optional) in the keyring. -func (c *ChainClient) AccountCreate(accountName, mnemonic, hdPath string) error { - if mnemonic == "" { - entropySeed, err := bip39.NewEntropy(256) - if err != nil { - return err - } - mnemonic, err = bip39.NewMnemonic(entropySeed) - fmt.Println("mnemoniccccc here.....", mnemonic) - if err != nil { - return err - } - } - - algos, _ := c.clientCtx.Keyring.SupportedAlgorithms() - algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algos) - if err != nil { - return err - } - - info, err := c.clientCtx.Keyring.NewAccount(accountName, mnemonic, "", hdPath, algo) - if err != nil { - return err - } - pk, err := info.GetPubKey() - if err != nil { - return err - } - addr := sdk.AccAddress(pk.Address()) - fmt.Println("address hereee...", addr) - // account := c.ToAccount(info) - // account.Mnemonic = mnemonic - return nil -} - -// func initSDKConfig() { -// // sdkConfig := sdk.GetConfig() -// // bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix() -// // sdkConfig.SetBech32PrefixForAccount(config.Bech32PrefixAccAddr(), config.Bech32PrefixAccPub()) -// // sdkConfig.SetBech32PrefixForValidator(config.Bech32PrefixValAddr(), config.Bech32PrefixValPub()) -// // sdkConfig.SetBech32PrefixForConsensusNode(config.Bech32PrefixConsAddr(), config.Bech32PrefixConsPub()) -// } - -func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, cdc codec.BinaryCodec, out io.Writer, address string) client.Context { - encodingConfig := MakeEncodingConfig() - authtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) - cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) - sdk.RegisterInterfaces(encodingConfig.InterfaceRegistry) - staking.RegisterInterfaces(encodingConfig.InterfaceRegistry) - cryptocodec.RegisterInterfaces(encodingConfig.InterfaceRegistry) - - // chainID := ctx.ChainID() - - // fmt.Println("address heree......", address) - fromAddress := sdk.AccAddress(address) - // Assuming you have access to the keyring and broadcast mode - broadcastMode := "block" - - homepath := "/home/vitwit/.availsdk/keyring-test" - - return client.Context{}. - WithCodec(cdc.(codec.Codec)). - WithChainID(chainID). - WithFromAddress(fromAddress). - WithFromName("alice"). - WithKeyringDir(homepath). - WithBroadcastMode(broadcastMode). - WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). - WithKeyring(kr). - WithAccountRetriever(authtypes.AccountRetriever{}). - WithOutput(out).WithClient(c).WithInterfaceRegistry(encodingConfig.InterfaceRegistry) -} - -// NewFactory creates a new Factory. -func NewFactory(clientCtx client.Context) tx.Factory { - return tx.Factory{}. - WithChainID(clientCtx.ChainID). - WithKeybase(clientCtx.Keyring). - // WithGas(defaultGasLimit). - // WithGasAdjustment(defaultGasAdjustment). - WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). - WithAccountRetriever(clientCtx.AccountRetriever). - WithTxConfig(clientCtx.TxConfig) -} - -// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. -func MakeEncodingConfig() EncodingConfig { - aminoCodec := codec.NewLegacyAmino() - interfaceRegistry := codectypes.NewInterfaceRegistry() - codec := codec.NewProtoCodec(interfaceRegistry) - txCfg := authTx.NewTxConfig(codec, authTx.DefaultSignModes) - - encCfg := EncodingConfig{ - InterfaceRegistry: interfaceRegistry, - Codec: codec, - TxConfig: txCfg, - Amino: aminoCodec, - } - - std.RegisterLegacyAminoCodec(encCfg.Amino) - std.RegisterInterfaces(encCfg.InterfaceRegistry) - // mb.RegisterLegacyAminoCodec(encCfg.Amino) - // mb.RegisterInterfaces(encCfg.InterfaceRegistry) - - return encCfg -} - -// EncodingConfig specifies the concrete encoding types to use for a given app. -// This is provided for compatibility between protobuf and amino implementations. -type EncodingConfig struct { - InterfaceRegistry codectypes.InterfaceRegistry - Codec codec.Codec - TxConfig client.TxConfig - Amino *codec.LegacyAmino -} - -// AccountList returns a list of accounts. -// func (c *ChainClient) AccountList() (accounts []sdk.Account, err error) { -// infos, err := c.clientCtx.Keyring.List() -// if err != nil { -// return nil, err -// } -// for _, info := range infos { -// accounts = append(accounts, c.ToAccount(info)) -// } -// return accounts, nil -// } diff --git a/keeper/abci.go b/keeper/abci.go index 195c507..e728883 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -59,7 +59,8 @@ func (h *ProofOfBlobProposalHandler) PrepareProposal(ctx sdk.Context, req *abci. ExtendedCommitInfo: req.LocalLastCommit, } - fmt.Println("votes..................", votes, injectedVoteExtTx) + fmt.Println("votes..................", votes) + fmt.Println("injectedVoteExtTx............", injectedVoteExtTx.ExtendedCommitInfo.String()) bz, err := json.Marshal(injectedVoteExtTx) if err != nil { diff --git a/keeper/client.go b/keeper/client.go index 27796d6..3f14e36 100644 --- a/keeper/client.go +++ b/keeper/client.go @@ -1,102 +1,80 @@ package keeper -import ( - "fmt" - - cometrpc "github.com/cometbft/cometbft/rpc/client/http" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/std" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/tx/signing" - authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/go-bip39" - - // "github.com/tendermint/starport/starport/pkg/xfilepath" - - "github.com/cosmos/cosmos-sdk/types/module" -) - -const ( - defaultGasAdjustment = 1.0 - defaultGasLimit = 300000 -) - -// var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) - -func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, - cdc codec.BinaryCodec, homepath string, fromAddress sdk.AccAddress) client.Context { - encodingConfig := MakeEncodingConfig() - - broadcastMode := flags.BroadcastSync - - // homepath := "/home/vitwit/.availsdk" - - return client.Context{}. - WithCodec(cdc.(codec.Codec)). - WithChainID(chainID). - WithFromAddress(fromAddress). - WithFromName("testkey"). - WithKeyringDir(homepath). - WithBroadcastMode(broadcastMode). - WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). - WithKeyring(kr). - WithAccountRetriever(authtypes.AccountRetriever{}). - WithClient(c).WithInterfaceRegistry(encodingConfig.InterfaceRegistry). - WithSkipConfirmation(true) -} - -// NewFactory creates a new Factory. -func NewFactory(clientCtx client.Context) tx.Factory { - return tx.Factory{}. - WithChainID(clientCtx.ChainID). - WithKeybase(clientCtx.Keyring). - WithGas(defaultGasLimit). - WithGasAdjustment(defaultGasAdjustment). - WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). - WithAccountRetriever(clientCtx.AccountRetriever). - WithTxConfig(clientCtx.TxConfig) -} - -// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. -func MakeEncodingConfig(modules ...module.AppModuleBasic) EncodingConfig { - aminoCodec := codec.NewLegacyAmino() - interfaceRegistry := codectypes.NewInterfaceRegistry() - codec := codec.NewProtoCodec(interfaceRegistry) - txCfg := authTx.NewTxConfig(codec, authTx.DefaultSignModes) - - encCfg := EncodingConfig{ - InterfaceRegistry: interfaceRegistry, - Codec: codec, - TxConfig: txCfg, - Amino: aminoCodec, - } - - mb := module.NewBasicManager(modules...) - - std.RegisterLegacyAminoCodec(encCfg.Amino) - std.RegisterInterfaces(encCfg.InterfaceRegistry) - mb.RegisterLegacyAminoCodec(encCfg.Amino) - mb.RegisterInterfaces(encCfg.InterfaceRegistry) - - return encCfg -} - -// func MakeTestEncodingConfig(modules ...module.AppModuleBasic) TestEncodingConfig { +// import ( +// "fmt" + +// cometrpc "github.com/cometbft/cometbft/rpc/client/http" +// "github.com/cosmos/cosmos-sdk/client" +// "github.com/cosmos/cosmos-sdk/client/flags" +// "github.com/cosmos/cosmos-sdk/client/tx" +// "github.com/cosmos/cosmos-sdk/codec" +// codectypes "github.com/cosmos/cosmos-sdk/codec/types" +// "github.com/cosmos/cosmos-sdk/crypto/hd" +// "github.com/cosmos/cosmos-sdk/crypto/keyring" +// "github.com/cosmos/cosmos-sdk/std" +// sdk "github.com/cosmos/cosmos-sdk/types" +// "github.com/cosmos/cosmos-sdk/types/tx/signing" +// authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" +// authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +// "github.com/cosmos/go-bip39" + +// // "github.com/tendermint/starport/starport/pkg/xfilepath" + +// "github.com/cosmos/cosmos-sdk/types/module" +// ) + +// const ( +// defaultGasAdjustment = 1.0 +// defaultGasLimit = 300000 +// ) + +// // var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) + +// func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, +// cdc codec.BinaryCodec, homepath string, fromAddress sdk.AccAddress) client.Context { +// encodingConfig := MakeEncodingConfig() + +// broadcastMode := flags.BroadcastSync + +// // homepath := "/home/vitwit/.availsdk" + +// return client.Context{}. +// WithCodec(cdc.(codec.Codec)). +// WithChainID(chainID). +// WithFromAddress(fromAddress). +// WithFromName("testkey"). +// WithKeyringDir(homepath). +// WithBroadcastMode(broadcastMode). +// WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). +// WithKeyring(kr). +// WithAccountRetriever(authtypes.AccountRetriever{}). +// WithClient(c).WithInterfaceRegistry(encodingConfig.InterfaceRegistry). +// WithSkipConfirmation(true) +// } + +// // NewFactory creates a new Factory. +// func NewFactory(clientCtx client.Context) tx.Factory { +// return tx.Factory{}. +// WithChainID(clientCtx.ChainID). +// WithKeybase(clientCtx.Keyring). +// WithGas(defaultGasLimit). +// WithGasAdjustment(defaultGasAdjustment). +// WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). +// WithAccountRetriever(clientCtx.AccountRetriever). +// WithTxConfig(clientCtx.TxConfig) +// } + +// // MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. +// func MakeEncodingConfig(modules ...module.AppModuleBasic) EncodingConfig { // aminoCodec := codec.NewLegacyAmino() -// interfaceRegistry := testutil.CodecOptions{}.NewInterfaceRegistry() +// interfaceRegistry := codectypes.NewInterfaceRegistry() // codec := codec.NewProtoCodec(interfaceRegistry) +// txCfg := authTx.NewTxConfig(codec, authTx.DefaultSignModes) -// encCfg := TestEncodingConfig{ +// encCfg := EncodingConfig{ // InterfaceRegistry: interfaceRegistry, // Codec: codec, -// TxConfig: tx.NewTxConfig(codec, tx.DefaultSignModes), +// TxConfig: txCfg, // Amino: aminoCodec, // } @@ -110,71 +88,93 @@ func MakeEncodingConfig(modules ...module.AppModuleBasic) EncodingConfig { // return encCfg // } -// EncodingConfig specifies the concrete encoding types to use for a given app. -// This is provided for compatibility between protobuf and amino implementations. -type EncodingConfig struct { - InterfaceRegistry codectypes.InterfaceRegistry - Codec codec.Codec - TxConfig client.TxConfig - Amino *codec.LegacyAmino -} - -// ImportMnemonic is to import existing account mnemonic in keyring -func ImportMnemonic(keyName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { - info, err := AccountCreate(keyName, mnemonic, hdPath, c) // return account also - // fmt.Println("here the accc details.......", keyName, mnemonic, hdPath) - if err != nil { - return nil, err - } - - return info, nil -} - -// AccountCreate creates an account by name and mnemonic (optional) in the keyring. -func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { - if mnemonic == "" { - entropySeed, err := bip39.NewEntropy(256) - if err != nil { - return nil, err - } - mnemonic, err = bip39.NewMnemonic(entropySeed) - fmt.Println("mnemoniccccc here.....", mnemonic) - if err != nil { - return nil, err - } - } - - algos, _ := c.Keyring.SupportedAlgorithms() - algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algos) - if err != nil { - return nil, err - } - - path := hd.CreateHDPath(118, 0, 0).String() - // fmt.Println("pathhh......", path) - - // record, str, err := c.Keyring.NewMnemonic("test_key1", keyring.English, path, keyring.DefaultBIP39Passphrase, hd.Secp256k1) - // fmt.Println("recorddddd.......", err, str, record) - - // k, _, err = kb.NewMnemonic("test", English, types.FullFundraiserPath, DefaultBIP39Passphrase, hd.Secp256k1) - info, err := c.Keyring.NewAccount(accountName, mnemonic, keyring.DefaultBIP39Passphrase, path, algo) - fmt.Println("after creationnnn.........", info, err) - if err != nil { - return nil, err - } - // pk, err := info.GetPubKey() - // if err != nil { - // return nil, err - // } - - // addr := sdk.AccAddress(pk.Address()) - // fmt.Println("address hereee...", addr) - - // aa, err := info.GetAddress() - // fmt.Println("here aa and err.......", aa, err) - - // account := c.ToAccount(info) - // account.Mnemonic = mnemonic - return info, nil - // return nil -} +// // func MakeTestEncodingConfig(modules ...module.AppModuleBasic) TestEncodingConfig { +// // aminoCodec := codec.NewLegacyAmino() +// // interfaceRegistry := testutil.CodecOptions{}.NewInterfaceRegistry() +// // codec := codec.NewProtoCodec(interfaceRegistry) + +// // encCfg := TestEncodingConfig{ +// // InterfaceRegistry: interfaceRegistry, +// // Codec: codec, +// // TxConfig: tx.NewTxConfig(codec, tx.DefaultSignModes), +// // Amino: aminoCodec, +// // } + +// // mb := module.NewBasicManager(modules...) + +// // std.RegisterLegacyAminoCodec(encCfg.Amino) +// // std.RegisterInterfaces(encCfg.InterfaceRegistry) +// // mb.RegisterLegacyAminoCodec(encCfg.Amino) +// // mb.RegisterInterfaces(encCfg.InterfaceRegistry) + +// // return encCfg +// // } + +// // EncodingConfig specifies the concrete encoding types to use for a given app. +// // This is provided for compatibility between protobuf and amino implementations. +// type EncodingConfig struct { +// InterfaceRegistry codectypes.InterfaceRegistry +// Codec codec.Codec +// TxConfig client.TxConfig +// Amino *codec.LegacyAmino +// } + +// // ImportMnemonic is to import existing account mnemonic in keyring +// func ImportMnemonic(keyName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { +// info, err := AccountCreate(keyName, mnemonic, hdPath, c) // return account also +// // fmt.Println("here the accc details.......", keyName, mnemonic, hdPath) +// if err != nil { +// return nil, err +// } + +// return info, nil +// } + +// // AccountCreate creates an account by name and mnemonic (optional) in the keyring. +// func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { +// if mnemonic == "" { +// entropySeed, err := bip39.NewEntropy(256) +// if err != nil { +// return nil, err +// } +// mnemonic, err = bip39.NewMnemonic(entropySeed) +// fmt.Println("mnemoniccccc here.....", mnemonic) +// if err != nil { +// return nil, err +// } +// } + +// algos, _ := c.Keyring.SupportedAlgorithms() +// algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algos) +// if err != nil { +// return nil, err +// } + +// path := hd.CreateHDPath(118, 0, 0).String() +// // fmt.Println("pathhh......", path) + +// // record, str, err := c.Keyring.NewMnemonic("test_key1", keyring.English, path, keyring.DefaultBIP39Passphrase, hd.Secp256k1) +// // fmt.Println("recorddddd.......", err, str, record) + +// // k, _, err = kb.NewMnemonic("test", English, types.FullFundraiserPath, DefaultBIP39Passphrase, hd.Secp256k1) +// info, err := c.Keyring.NewAccount(accountName, mnemonic, keyring.DefaultBIP39Passphrase, path, algo) +// fmt.Println("after creationnnn.........", info, err) +// if err != nil { +// return nil, err +// } +// // pk, err := info.GetPubKey() +// // if err != nil { +// // return nil, err +// // } + +// // addr := sdk.AccAddress(pk.Address()) +// // fmt.Println("address hereee...", addr) + +// // aa, err := info.GetAddress() +// // fmt.Println("here aa and err.......", aa, err) + +// // account := c.ToAccount(info) +// // account.Mnemonic = mnemonic +// return info, nil +// // return nil +// } diff --git a/keeper/submitBlobTx.go b/keeper/submitBlobTx.go deleted file mode 100644 index 76158a4..0000000 --- a/keeper/submitBlobTx.go +++ /dev/null @@ -1,113 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/codec" - - sdk "github.com/cosmos/cosmos-sdk/types" - - dacli "github.com/vitwit/avail-da-module/chainclient" - "github.com/vitwit/avail-da-module/types" -) - -func (k Keeper) SubmitBlobTx2(ctx sdk.Context, msg types.MsgSubmitBlobRequest) error { - cdc := k.cdc - homepath := "/home/vitwit/.availsdk" - - cc, err := dacli.CreateChainClient(sdk.KeyringServiceName(), ctx.ChainID(), homepath, cdc.(codec.Codec)) - if err != nil { - return err - } - - msg.ValidatorAddress = cc.Address - err = cc.BroadcastTx(msg, cc.Key, sdk.AccAddress(cc.Address)) - if err != nil { - fmt.Println("error while broadcastig the txxx.........", err) - return err - } - - return nil -} - -// func SubmitBlobTx(ctx sdk.Context, msg types.MsgSubmitBlobRequest, cdc codec.Codec) error { -// // Define keyring and RPC client configuration - -// homePath := "/home/vitwit/.availsdk" -// keyName := "alice" -// rpcAddress := "http://localhost:26657" - -// // Create a keyring -// kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, homePath, os.Stdin, cdc) -// if err != nil { -// return fmt.Errorf("error creating keyring: %w", err) -// } - -// // List all keys in the keyring -// // keys, err := kr.List() -// // if err != nil { -// // fmt.Println("error listing keys:", err) -// // } - -// info, err := kr.Key(keyName) -// // log.Println("uuu....", info, err) - -// valAddr, err := info.GetAddress() - -// // valAddr, err := sdk.AccAddressFromBech32(addr.String()) -// // fmt.Println("val addr, err..", valAddr, err, addr) - -// // fmt.Println("keysss........", keys) - -// // // Print out the keys -// // for _, keyInfo := range keys { -// // addr, err := keyInfo.GetAddress() -// // fmt.Println("err..", err) -// // fmt.Printf("Name: %s, Address: %s\n", keyInfo.Name, addr) -// // } - -// // Create an RPC client -// rpcClient, err := cometrpc.NewWithTimeout(rpcAddress, "/websocket", 3) -// if err != nil { -// return fmt.Errorf("error creating RPC client: %w", err) -// } - -// // Create a new client context -// clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc, homePath, valAddr) - -// // Retrieve the validator address (replace with actual logic to get the address) -// // valAddr, err = sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") -// // if err != nil { -// // return fmt.Errorf("error parsing validator address: %w", err) -// // } - -// // Set the client context's from fields -// clientCtx.FromName = keyName -// clientCtx.FromAddress = valAddr - -// // Fetch account number and sequence from the blockchain -// accountRetriever := authtypes.AccountRetriever{} -// account, err := accountRetriever.GetAccount(clientCtx, valAddr) -// if err != nil { -// return fmt.Errorf("error retrieving account: %w", err) -// } - -// fmt.Println("account details......", account.GetAccountNumber(), account.GetSequence()) - -// // Set the correct account number and sequence -// factory := NewFactory(clientCtx). -// WithAccountNumber(account.GetAccountNumber()). -// WithSequence(account.GetSequence()) - -// // Create a transaction factory and set the validator address in the message -// // factory := NewFactory(clientCtx) -// msg.ValidatorAddress = valAddr.String() -// // time.Sleep(10 * time.Second) - -// // Generate and broadcast the transaction -// if err := clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg); err != nil { -// return fmt.Errorf("error broadcasting transaction: %w", err) -// } - -// return nil -// } diff --git a/relayer/client.go b/relayer/client.go index 0facf72..bf6b648 100644 --- a/relayer/client.go +++ b/relayer/client.go @@ -36,8 +36,6 @@ func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, broadcastMode := flags.BroadcastSync - // homepath := "/home/vitwit/.availsdk" - return client.Context{}. WithCodec(cdc.(codec.Codec)). WithChainID(chainID). @@ -88,28 +86,6 @@ func MakeEncodingConfig(modules ...module.AppModuleBasic) EncodingConfig { return encCfg } -// func MakeTestEncodingConfig(modules ...module.AppModuleBasic) TestEncodingConfig { -// aminoCodec := codec.NewLegacyAmino() -// interfaceRegistry := testutil.CodecOptions{}.NewInterfaceRegistry() -// codec := codec.NewProtoCodec(interfaceRegistry) - -// encCfg := TestEncodingConfig{ -// InterfaceRegistry: interfaceRegistry, -// Codec: codec, -// TxConfig: tx.NewTxConfig(codec, tx.DefaultSignModes), -// Amino: aminoCodec, -// } - -// mb := module.NewBasicManager(modules...) - -// std.RegisterLegacyAminoCodec(encCfg.Amino) -// std.RegisterInterfaces(encCfg.InterfaceRegistry) -// mb.RegisterLegacyAminoCodec(encCfg.Amino) -// mb.RegisterInterfaces(encCfg.InterfaceRegistry) - -// return encCfg -// } - // EncodingConfig specifies the concrete encoding types to use for a given app. // This is provided for compatibility between protobuf and amino implementations. type EncodingConfig struct { @@ -122,7 +98,6 @@ type EncodingConfig struct { // ImportMnemonic is to import existing account mnemonic in keyring func ImportMnemonic(keyName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { info, err := AccountCreate(keyName, mnemonic, hdPath, c) // return account also - // fmt.Println("here the accc details.......", keyName, mnemonic, hdPath) if err != nil { return nil, err } @@ -138,7 +113,6 @@ func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) (*key return nil, err } mnemonic, err = bip39.NewMnemonic(entropySeed) - fmt.Println("mnemoniccccc here.....", mnemonic) if err != nil { return nil, err } @@ -176,5 +150,4 @@ func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) (*key // account := c.ToAccount(info) // account.Mnemonic = mnemonic return info, nil - // return nil } diff --git a/relayer/publish.go b/relayer/publish.go index 87ec3d8..8cd5d3e 100644 --- a/relayer/publish.go +++ b/relayer/publish.go @@ -2,16 +2,12 @@ package relayer import ( "fmt" - "os" - cometrpc "github.com/cometbft/cometbft/rpc/client/http" - clitx "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/vitwit/avail-da-module/types" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + dacli "github.com/vitwit/avail-da-module/chainclient" ) // PostNextBlocks is called by the current proposing validator during PrepareProposal. @@ -106,7 +102,7 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo ) // TODO : execute tx about failure submission - err = ExecuteTX(ctx, types.MsgUpdateBlobStatusRequest{ + err = dacli.ExecuteTX(ctx, types.MsgUpdateBlobStatusRequest{ ValidatorAddress: sdk.AccAddress.String(proposer), BlocksRange: &types.Range{ From: uint64(blocks[0]), @@ -137,7 +133,7 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo fmt.Println("submit blocks msg.......", msg) // TODO : execute tx about successfull submission - err = ExecuteTX(ctx, msg, cdc) + err = dacli.ExecuteTX(ctx, msg, cdc) if err != nil { fmt.Println("error while submitting tx...", err) } @@ -145,85 +141,100 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo } -func ExecuteTX(ctx sdk.Context, msg types.MsgUpdateBlobStatusRequest, cdc codec.BinaryCodec) error { - // Define keyring and RPC client configuration - - homePath := "/home/vitwit/.availsdk" - keyName := "alice" - rpcAddress := "http://localhost:26657" - - // Create a keyring - kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, homePath, os.Stdin, cdc.(codec.Codec)) - if err != nil { - return fmt.Errorf("error creating keyring: %w", err) - } - - // List all keys in the keyring - // keys, err := kr.List() - // if err != nil { - // fmt.Println("error listing keys:", err) - // } - - info, err := kr.Key(keyName) - // log.Println("uuu....", info, err) - fmt.Println("here error???", info == nil) - valAddr, err := info.GetAddress() - fmt.Println("after address................", valAddr) - - // valAddr, err := sdk.AccAddressFromBech32(addr.String()) - // fmt.Println("val addr, err..", valAddr, err, addr) - - // fmt.Println("keysss........", keys) - - // // Print out the keys - // for _, keyInfo := range keys { - // addr, err := keyInfo.GetAddress() - // fmt.Println("err..", err) - // fmt.Printf("Name: %s, Address: %s\n", keyInfo.Name, addr) - // } - - // Create an RPC client - rpcClient, err := cometrpc.NewWithTimeout(rpcAddress, "/websocket", 3) - if err != nil { - return fmt.Errorf("error creating RPC client: %w", err) - } - - // Create a new client context - clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc, homePath, valAddr) - - // Retrieve the validator address (replace with actual logic to get the address) - // valAddr, err = sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") - // if err != nil { - // return fmt.Errorf("error parsing validator address: %w", err) - // } - - // Set the client context's from fields - clientCtx.FromName = keyName - clientCtx.FromAddress = valAddr - - // Fetch account number and sequence from the blockchain - accountRetriever := authtypes.AccountRetriever{} - account, err := accountRetriever.GetAccount(clientCtx, valAddr) - if err != nil { - return fmt.Errorf("error retrieving account: %w", err) - } - - fmt.Println("account details......", account.GetAccountNumber(), account.GetSequence()) - - // Set the correct account number and sequence - factory := NewFactory(clientCtx). - WithAccountNumber(account.GetAccountNumber()). - WithSequence(account.GetSequence()) - - // Create a transaction factory and set the validator address in the message - // factory := NewFactory(clientCtx) - msg.ValidatorAddress = valAddr.String() - // time.Sleep(10 * time.Second) - - // Generate and broadcast the transaction - if err := clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg); err != nil { - return fmt.Errorf("error broadcasting transaction: %w", err) - } - - return nil -} +// var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) + +// availdHomePath := filepath.Join(os.Getenv("HOME"), "availsdk") + +// func GetBinPath() string { +// homeDir, err := os.UserHomeDir() +// if err != nil { +// log.Fatal(err) +// } + +// availdHomePath := filepath.Join(homeDir, ".availsdk") +// fmt.Println("availdHonmePath.......", availdHomePath) +// return availdHomePath +// } + +// func ExecuteTX(ctx sdk.Context, msg types.MsgUpdateBlobStatusRequest, cdc codec.BinaryCodec) error { +// // Define keyring and RPC client configuration + +// // homePath := "/home/vitwit/.availsdk" +// homePath := GetBinPath() +// fmt.Println("get key namee.........", os.Getenv("KEY")) +// keyName := os.Getenv("KEY") +// rpcAddress := "http://localhost:26657" + +// // Create a keyring +// kr, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, homePath, os.Stdin, cdc.(codec.Codec)) +// if err != nil { +// return fmt.Errorf("error creating keyring: %w", err) +// } + +// // List all keys in the keyring +// // keys, err := kr.List() +// // if err != nil { +// // fmt.Println("error listing keys:", err) +// // } + +// info, err := kr.Key(keyName) +// valAddr, err := info.GetAddress() +// fmt.Println("after address................", valAddr) + +// // valAddr, err := sdk.AccAddressFromBech32(addr.String()) +// // fmt.Println("val addr, err..", valAddr, err, addr) + +// // fmt.Println("keysss........", keys) + +// // // Print out the keys +// // for _, keyInfo := range keys { +// // addr, err := keyInfo.GetAddress() +// // fmt.Println("err..", err) +// // fmt.Printf("Name: %s, Address: %s\n", keyInfo.Name, addr) +// // } + +// // Create an RPC client +// rpcClient, err := cometrpc.NewWithTimeout(rpcAddress, "/websocket", 3) +// if err != nil { +// return fmt.Errorf("error creating RPC client: %w", err) +// } + +// // Create a new client context +// clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc, homePath, valAddr) + +// // Retrieve the validator address (replace with actual logic to get the address) +// // valAddr, err = sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") +// // if err != nil { +// // return fmt.Errorf("error parsing validator address: %w", err) +// // } + +// // Set the client context's from fields +// clientCtx.FromName = keyName +// clientCtx.FromAddress = valAddr + +// // Fetch account number and sequence from the blockchain +// accountRetriever := authtypes.AccountRetriever{} +// account, err := accountRetriever.GetAccount(clientCtx, valAddr) +// if err != nil { +// return fmt.Errorf("error retrieving account: %w", err) +// } + +// fmt.Println("account details......", account.GetAccountNumber(), account.GetSequence()) + +// // Set the correct account number and sequence +// factory := NewFactory(clientCtx). +// WithAccountNumber(account.GetAccountNumber()). +// WithSequence(account.GetSequence()) + +// // Create a transaction factory and set the validator address in the message +// // factory := NewFactory(clientCtx) +// msg.ValidatorAddress = valAddr.String() +// // time.Sleep(10 * time.Second) + +// // Generate and broadcast the transaction +// if err := clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg); err != nil { +// return fmt.Errorf("error broadcasting transaction: %w", err) +// } + +// return nil +// } From fc44ca60fb2da5ee14f0e0416be8e8ffc60c2266 Mon Sep 17 00:00:00 2001 From: saiteja Date: Thu, 5 Sep 2024 15:15:40 +0530 Subject: [PATCH 39/58] feat: enable vote extensions --- keeper/abci.go | 68 +++++------ keeper/keeper.go | 47 +++----- keeper/status.go | 37 ++++++ keeper/store.go | 10 +- keeper/vote_entension.go | 28 +++-- keys.go | 2 + proto/sdk/avail/v1beta1/query.proto | 2 + types/query.pb.go | 174 ++++++++++++++++++++-------- 8 files changed, 243 insertions(+), 125 deletions(-) create mode 100644 keeper/status.go diff --git a/keeper/abci.go b/keeper/abci.go index 195c507..b635664 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -41,13 +41,6 @@ func (h *ProofOfBlobProposalHandler) PrepareProposal(ctx sdk.Context, req *abci. h.keeper.proposerAddress = req.ProposerAddress proposalTxs := req.Txs - // h.voteExtHandler.ExtendVoteHandler()(nil,err) - - // resp, err := h.prepareProposalHandler(ctx, req) - // if err != nil { - // return nil, err - // } - votes, err := h.aggregateVotes(ctx, req.LocalLastCommit) if err != nil { fmt.Println("error while aggregating votes", err) @@ -59,12 +52,11 @@ func (h *ProofOfBlobProposalHandler) PrepareProposal(ctx sdk.Context, req *abci. ExtendedCommitInfo: req.LocalLastCommit, } - fmt.Println("votes..................", votes, injectedVoteExtTx) + fmt.Println("votes..................", votes) bz, err := json.Marshal(injectedVoteExtTx) if err != nil { fmt.Println("failed to encode injected vote extension tx", "err", err) - // return nil, errors.New("failed to encode injected vote extension tx") } proposalTxs = append(proposalTxs, bz) @@ -84,33 +76,49 @@ func (h *ProofOfBlobProposalHandler) ProcessProposal(ctx sdk.Context, req *abci. // return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } - fmt.Println("injected data is:..............", injectedVoteExtTx) + //TODO: write some validations + return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil } func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { fmt.Println("coming hereee.........", ctx.BlockHeight()) + votingEndHeight := k.GetVotingEndHeightFromStore(ctx) + blobStatus := k.GetBlobStatus(ctx) + currentHeight := ctx.BlockHeight() + + if len(req.Txs) > 0 && currentHeight == int64(votingEndHeight) && blobStatus == IN_VOTING_STATE { + var injectedVoteExtTx StakeWeightedVotes + if err := json.Unmarshal(req.Txs[0], &injectedVoteExtTx); err != nil { + fmt.Println("preblocker failed to decode injected vote extension tx", "err", err) + } else { + from := k.GetStartHeightFromStore(ctx) + to := k.GetEndHeightFromStore(ctx) + + pendingRangeKey := Key(from, to) + votingPower := injectedVoteExtTx.Votes[pendingRangeKey] + + if votingPower > 0 { + k.setBlobStatusSuccess(ctx) + } else { + k.SetBlobStatusFailure(ctx) + } + } + } currentBlockHeight := ctx.BlockHeight() if !k.IsValidBlockToPostTODA(uint64(currentBlockHeight)) { return nil } - // fmt.Printf("Ctx.........%+v\n", ctx) - - fmt.Println("block heighttt.........", ctx.BlockHeight(), ctx.ExecMode(), ctx.IsCheckTx(), ctx.IsReCheckTx()) - provenHeight := k.GetProvenHeightFromStore(ctx) fromHeight := provenHeight + 1 - fmt.Println("from height..", fromHeight) endHeight := min(fromHeight+uint64(k.MaxBlocksForBlob), uint64(ctx.BlockHeight())) //exclusive i.e [fromHeight, endHeight) - fmt.Println("end height..", endHeight-1) sdkCtx := sdk.UnwrapSDKContext(ctx) - err := k.SetBlobStatusPending(sdkCtx, fromHeight, endHeight-1) - if err != nil { - fmt.Println("error while setting blob status...", err) + ok := k.SetBlobStatusPending(sdkCtx, fromHeight, endHeight-1) + if !ok { return nil } @@ -120,27 +128,16 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err blocksToSumit = append(blocksToSumit, int64(i)) } - fmt.Println("blocks to submittttttttt.........", blocksToSumit) - // only proposar should should run the this if bytes.Equal(req.ProposerAddress, k.proposerAddress) { - // update blob status to success - // err = k.SetBlobStatusSuccess(sdkCtx, fromHeight, endHeight) - // if err != nil { - // return nil - // } - - // Todo: run the relayer routine - // relayer doesn't have to make submitBlob Transaction, it should just start DA submission k.relayer.PostBlocks(ctx, blocksToSumit, k.cdc, req.ProposerAddress) - } return nil } func (k *Keeper) IsValidBlockToPostTODA(height uint64) bool { - if uint64(height) <= uint64(1) { + if height <= uint64(1) { return false } @@ -161,7 +158,7 @@ func (h *ProofOfBlobProposalHandler) aggregateVotes(ctx sdk.Context, ci abci.Ext var totalStake int64 for _, v := range ci.Votes { - // TODO: why?? + // if a validator did not vote for a block, his vote extension should not be processed if v.BlockIdFlag != cmtproto.BlockIDFlagCommit { continue } @@ -169,9 +166,14 @@ func (h *ProofOfBlobProposalHandler) aggregateVotes(ctx sdk.Context, ci abci.Ext var voteExt VoteExtension if err := json.Unmarshal(v.VoteExtension, &voteExt); err != nil { h.VoteExtHandler.logger.Error("failed to decode vote extension", "err", err, "validator", fmt.Sprintf("%x", v.Validator.Address)) - //return nil, err + continue + } + + if voteExt.Votes == nil { + continue } + // TODO: remove if this is not used anywhere totalStake += v.Validator.Power for voteRange, isVoted := range voteExt.Votes { diff --git a/keeper/keeper.go b/keeper/keeper.go index 87af593..9cb6061 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -1,7 +1,6 @@ package keeper import ( - "encoding/binary" "errors" "fmt" @@ -42,6 +41,7 @@ type Keeper struct { publishToAvailBlockInterval int PublishToAvailBlockInterval uint64 MaxBlocksForBlob uint + VotingInterval uint64 injectedProofsLimit int app_id int @@ -82,8 +82,9 @@ func NewKeeper( app_id: appId, unprovenBlocks: make(map[int64][]byte), - MaxBlocksForBlob: 10, //Todo: call this from app.go, later change to params + MaxBlocksForBlob: 20, //Todo: call this from app.go, later change to params PublishToAvailBlockInterval: 5, //Todo: call this from app.go, later change to params + VotingInterval: 5, } } @@ -91,18 +92,9 @@ func (k *Keeper) SetRelayer(r *relayer.Relayer) { k.relayer = r } -func (k *Keeper) SetBlobStatusPending(ctx sdk.Context, startHeight, endHeight uint64) error { - +func (k *Keeper) GetBlobStatus(ctx sdk.Context) uint32 { store := ctx.KVStore(k.storeKey) - - if !CanUpdateStatusToPending(store) { //TOodo: we should check for expiration too - return errors.New("a block range with same start height is already being processed") - } - - UpdateBlobStatus(ctx, store, PENDING_STATE) - UpdateStartHeight(ctx, store, startHeight) - UpdateEndHeight(ctx, store, endHeight) - return nil + return GetStatusFromStore(store) } // Todo: remove this method later @@ -127,11 +119,12 @@ func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatu return nil, errors.New("can update the status if it is not pending") } - newStatus := READY_STATE + newStatus := IN_VOTING_STATE if !req.IsSuccess { newStatus = FAILURE_STATE } else { - UpdateProvenHeight(ctx, store, endHeight) + currentHeight := ctx.BlockHeight() + UpdateVotingEndHeight(ctx, store, uint64(currentHeight)+k.VotingInterval) } UpdateBlobStatus(ctx, store, newStatus) @@ -139,22 +132,6 @@ func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatu return &types.MsgUpdateBlobStatusResponse{}, nil } -func (k *Keeper) CheckHeight(endHeight uint64) error { - // Step 1: Encode 41 into a byte slice - // var endHeight uint64 = 41 - heightBytes := make([]byte, 8) - binary.BigEndian.PutUint64(heightBytes, endHeight) - - fmt.Println("Encoded byte slice for 41:", heightBytes) - - // Step 2: Decode the byte slice back to a uint64 - decodedHeight := binary.BigEndian.Uint64(heightBytes) - - fmt.Println("Decoded height:", decodedHeight) - - return nil -} - func (k *Keeper) SubmitBlobStatus(ctx sdk.Context, _ *types.QuerySubmitBlobStatusRequest) (*types.QuerySubmitBlobStatusResponse, error) { // Todo: implement query store := ctx.KVStore(k.storeKey) @@ -162,9 +139,13 @@ func (k *Keeper) SubmitBlobStatus(ctx sdk.Context, _ *types.QuerySubmitBlobStatu endHeight := k.GetEndHeightFromStore(ctx) status := GetStatusFromStore(store) statusString := ParseStatus(status) + provenHeight := k.GetProvenHeightFromStore(ctx) + votingEndHeight := k.GetVotingEndHeightFromStore(ctx) return &types.QuerySubmitBlobStatusResponse{ - Range: &types.Range{From: startHeight, To: endHeight}, - Status: statusString, + Range: &types.Range{From: startHeight, To: endHeight}, + Status: statusString, + ProvenHeight: provenHeight, + LastBlobVotingEndsAt: votingEndHeight, }, nil } diff --git a/keeper/status.go b/keeper/status.go new file mode 100644 index 0000000..ed924f5 --- /dev/null +++ b/keeper/status.go @@ -0,0 +1,37 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (k *Keeper) SetBlobStatusPending(ctx sdk.Context, startHeight, endHeight uint64) bool { + + store := ctx.KVStore(k.storeKey) + + if !CanUpdateStatusToPending(store) { //TOodo: we should check for expiration too + return false + } + + UpdateBlobStatus(ctx, store, PENDING_STATE) + UpdateStartHeight(ctx, store, startHeight) + UpdateEndHeight(ctx, store, endHeight) + return true +} + +func (k *Keeper) setBlobStatusSuccess(ctx sdk.Context) error { + store := ctx.KVStore(k.storeKey) + endHeight := k.GetEndHeightFromStore(ctx) + + err := UpdateProvenHeight(ctx, store, endHeight) + if err != nil { + return err + } + return UpdateBlobStatus(ctx, store, READY_STATE) +} + +func (k *Keeper) SetBlobStatusFailure(ctx sdk.Context) error { + + store := ctx.KVStore(k.storeKey) + + return UpdateBlobStatus(ctx, store, FAILURE_STATE) +} diff --git a/keeper/store.go b/keeper/store.go index cc1d34c..dad583e 100644 --- a/keeper/store.go +++ b/keeper/store.go @@ -25,7 +25,7 @@ func ParseStatus(status uint32) string { case IN_VOTING_STATE: return "IN_VOTING" case FAILURE_STATE: - return "FAILUTE" + return "FAILURE" default: return "UNKNOWN" } @@ -76,6 +76,10 @@ func UpdateProvenHeight(ctx sdk.Context, store storetypes2.KVStore, provenHeight return updateHeight(store, availblob1.ProvenHeightKey, provenHeight) } +func UpdateVotingEndHeight(ctx sdk.Context, store storetypes2.KVStore, votingEndHeight uint64) error { + return updateHeight(store, availblob1.VotingEndHeightKey, votingEndHeight) +} + func updateHeight(store storetypes2.KVStore, key collections.Prefix, height uint64) error { heightBytes := make([]byte, 8) @@ -89,6 +93,10 @@ func (k *Keeper) GetProvenHeightFromStore(ctx sdk.Context) uint64 { return k.getHeight(ctx, availblob1.ProvenHeightKey) } +func (k *Keeper) GetVotingEndHeightFromStore(ctx sdk.Context) uint64 { + return k.getHeight(ctx, availblob1.VotingEndHeightKey) +} + func (k *Keeper) GetStartHeightFromStore(ctx sdk.Context) uint64 { return k.getHeight(ctx, availblob1.PrevHeightKey) } diff --git a/keeper/vote_entension.go b/keeper/vote_entension.go index 90adedc..20b31b4 100644 --- a/keeper/vote_entension.go +++ b/keeper/vote_entension.go @@ -46,26 +46,38 @@ func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { pendingRangeKey := Key(from, end) + blobStatus := h.Keeper.GetBlobStatus(ctx) + currentHeight := ctx.BlockHeight() + voteEndHeight := h.Keeper.GetVotingEndHeightFromStore(ctx) Votes := make(map[string]bool, 1) + + abciResponseVoteExt := &abci.ResponseExtendVote{} + + if currentHeight+1 != int64(voteEndHeight) || blobStatus != IN_VOTING_STATE { + voteExt := VoteExtension{ + Votes: Votes, + } + + //TODO: use better marshalling instead of json (eg: proto marshalling) + votesBytes, err := json.Marshal(voteExt) + if err != nil { + return nil, fmt.Errorf("failed to marshal vote extension: %w", err) + } + abciResponseVoteExt.VoteExtension = votesBytes + return abciResponseVoteExt, nil + } + Votes[pendingRangeKey] = true voteExt := VoteExtension{ Votes: Votes, } - fmt.Println("before marshalling....", voteExt) - //TODO: use proto marshalling instead votesBytes, err := json.Marshal(voteExt) if err != nil { return nil, fmt.Errorf("failed to marshal vote extension: %w", err) } - var AfterVoteExt VoteExtension - err = json.Unmarshal(votesBytes, &AfterVoteExt) - if err != nil { - fmt.Println("muurshalling error.......................") - } - return &abci.ResponseExtendVote{ VoteExtension: votesBytes, }, nil diff --git a/keys.go b/keys.go index 6e8edfb..d712512 100644 --- a/keys.go +++ b/keys.go @@ -34,6 +34,8 @@ var ( PrevHeightKey = collections.NewPrefix(7) NextHeightKey = collections.NewPrefix(8) + + VotingEndHeightKey = collections.NewPrefix(9) ) const ( diff --git a/proto/sdk/avail/v1beta1/query.proto b/proto/sdk/avail/v1beta1/query.proto index f3f0d7b..2a4a878 100644 --- a/proto/sdk/avail/v1beta1/query.proto +++ b/proto/sdk/avail/v1beta1/query.proto @@ -17,6 +17,8 @@ message QuerySubmitBlobStatusRequest { message QuerySubmitBlobStatusResponse { Range range = 1; string status = 2; + uint64 proven_height = 3; + uint64 last_blob_voting_ends_at = 4; } // Query defines the gRPC querier service. diff --git a/types/query.pb.go b/types/query.pb.go index cc0c50c..c8a72cc 100644 --- a/types/query.pb.go +++ b/types/query.pb.go @@ -72,8 +72,10 @@ var xxx_messageInfo_QuerySubmitBlobStatusRequest proto.InternalMessageInfo // query response type QuerySubmitBlobStatusResponse struct { - Range *Range `protobuf:"bytes,1,opt,name=range,proto3" json:"range,omitempty"` - Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"` + Range *Range `protobuf:"bytes,1,opt,name=range,proto3" json:"range,omitempty"` + Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"` + ProvenHeight uint64 `protobuf:"varint,3,opt,name=proven_height,json=provenHeight,proto3" json:"proven_height,omitempty"` + LastBlobVotingEndsAt uint64 `protobuf:"varint,4,opt,name=last_blob_voting_ends_at,json=lastBlobVotingEndsAt,proto3" json:"last_blob_voting_ends_at,omitempty"` } func (m *QuerySubmitBlobStatusResponse) Reset() { *m = QuerySubmitBlobStatusResponse{} } @@ -123,6 +125,20 @@ func (m *QuerySubmitBlobStatusResponse) GetStatus() string { return "" } +func (m *QuerySubmitBlobStatusResponse) GetProvenHeight() uint64 { + if m != nil { + return m.ProvenHeight + } + return 0 +} + +func (m *QuerySubmitBlobStatusResponse) GetLastBlobVotingEndsAt() uint64 { + if m != nil { + return m.LastBlobVotingEndsAt + } + return 0 +} + // QueryValidatorsRequest is the request type for the Query/Validators RPC method. type QueryValidatorsRequest struct { } @@ -616,54 +632,58 @@ func init() { func init() { proto.RegisterFile("sdk/avail/v1beta1/query.proto", fileDescriptor_30ff5d91ce731c68) } var fileDescriptor_30ff5d91ce731c68 = []byte{ - // 749 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xcd, 0x6e, 0xd3, 0x4a, - 0x14, 0xc7, 0xe3, 0x7e, 0xdd, 0xdb, 0x49, 0x7a, 0xd5, 0xce, 0x45, 0x25, 0x98, 0x36, 0x49, 0x5d, - 0x15, 0x52, 0x4a, 0x6d, 0x1a, 0x5e, 0x80, 0x46, 0xa0, 0xb2, 0x41, 0x02, 0x17, 0x81, 0x84, 0x84, - 0xa2, 0x71, 0x3d, 0x38, 0x56, 0x12, 0x8f, 0xeb, 0x19, 0x87, 0x76, 0xcb, 0x92, 0x55, 0xa5, 0x2e, - 0x10, 0x5b, 0x9e, 0x81, 0x87, 0xe8, 0xb2, 0x12, 0x1b, 0x56, 0x80, 0x5a, 0x1e, 0x04, 0x79, 0x3c, - 0x76, 0xed, 0x64, 0x5c, 0x85, 0x5d, 0x9c, 0xff, 0xf9, 0xf8, 0x9d, 0x99, 0xf9, 0x1f, 0xb0, 0x4a, - 0xed, 0x9e, 0x81, 0x86, 0xc8, 0xed, 0x1b, 0xc3, 0x1d, 0x0b, 0x33, 0xb4, 0x63, 0x1c, 0x86, 0x38, - 0x38, 0xd6, 0xfd, 0x80, 0x30, 0x02, 0x97, 0xa8, 0xdd, 0xd3, 0xb9, 0xac, 0x0b, 0x59, 0xbd, 0xe1, - 0x10, 0x87, 0x70, 0xd5, 0x88, 0x7e, 0xc5, 0x81, 0xea, 0x8a, 0x43, 0x88, 0xd3, 0xc7, 0x06, 0xf2, - 0x5d, 0x03, 0x79, 0x1e, 0x61, 0x88, 0xb9, 0xc4, 0xa3, 0x42, 0x5d, 0x1b, 0xef, 0x32, 0x44, 0x7d, - 0xd7, 0x46, 0x8c, 0x04, 0x22, 0xa4, 0x2e, 0x0a, 0xf0, 0x2f, 0x2b, 0x7c, 0x67, 0x30, 0x77, 0x80, - 0x29, 0x43, 0x03, 0x5f, 0x04, 0xa8, 0xe3, 0x35, 0xd8, 0x51, 0xac, 0x69, 0x35, 0xb0, 0xf2, 0x22, - 0xa2, 0xde, 0x0f, 0xad, 0x81, 0xcb, 0xda, 0x7d, 0x62, 0xed, 0x33, 0xc4, 0x42, 0x6a, 0xe2, 0xc3, - 0x10, 0x53, 0xa6, 0x39, 0x60, 0xb5, 0x40, 0xa7, 0x3e, 0xf1, 0x28, 0x86, 0x3a, 0x98, 0x0d, 0x90, - 0xe7, 0xe0, 0xaa, 0xd2, 0x50, 0x9a, 0xe5, 0x56, 0x55, 0x1f, 0x9b, 0x5b, 0x37, 0x23, 0xdd, 0x8c, - 0xc3, 0xe0, 0x32, 0x98, 0xa3, 0xbc, 0x42, 0x75, 0xaa, 0xa1, 0x34, 0xe7, 0x4d, 0xf1, 0xa5, 0x55, - 0xc1, 0x32, 0x6f, 0xf4, 0x2a, 0x99, 0x2e, 0x45, 0x78, 0x0b, 0x6e, 0x8e, 0x29, 0xa2, 0x79, 0x1b, - 0x80, 0xf4, 0x34, 0x68, 0x55, 0x69, 0x4c, 0x37, 0xcb, 0xad, 0x15, 0x09, 0x41, 0x9a, 0xda, 0x9e, - 0x39, 0xfb, 0x51, 0x2f, 0x99, 0x99, 0x2c, 0x6d, 0x0f, 0x54, 0x79, 0xf9, 0xdd, 0x28, 0x63, 0xd7, - 0xb6, 0x03, 0x4c, 0x93, 0xd6, 0x70, 0x0b, 0x2c, 0xa5, 0x91, 0x1d, 0x14, 0x6b, 0x7c, 0xd0, 0x79, - 0x73, 0x31, 0x15, 0x44, 0x8e, 0xf6, 0x08, 0xdc, 0x92, 0x14, 0x12, 0xa4, 0xeb, 0x60, 0x81, 0x23, - 0x8d, 0x54, 0xa9, 0xa0, 0x4c, 0xb0, 0xa6, 0x0a, 0x94, 0xe7, 0x01, 0x19, 0x62, 0xef, 0x29, 0x76, - 0x9d, 0x2e, 0x4b, 0x4e, 0x21, 0xa9, 0x9e, 0xd7, 0xae, 0xaa, 0xfb, 0xfc, 0xff, 0x4e, 0x97, 0x0b, - 0xbc, 0xfa, 0x8c, 0x59, 0xf1, 0x33, 0xc1, 0x1a, 0x05, 0xff, 0xb7, 0xfb, 0xe4, 0xa0, 0xf7, 0xda, - 0x65, 0xdd, 0x27, 0x47, 0xbe, 0x1b, 0xf0, 0x87, 0x16, 0x5d, 0x48, 0x26, 0x69, 0xda, 0x14, 0x5f, - 0xf0, 0x31, 0x00, 0x38, 0x8d, 0xe2, 0x97, 0x55, 0x6e, 0xa9, 0x7a, 0xfc, 0xd6, 0xf4, 0xe4, 0xad, - 0xe9, 0x2f, 0x93, 0xb7, 0xd6, 0xfe, 0x37, 0x3a, 0xd9, 0x93, 0x9f, 0x75, 0xc5, 0xcc, 0xe4, 0x69, - 0xb7, 0x13, 0x6c, 0xec, 0xd9, 0xae, 0xe7, 0x70, 0x80, 0xf4, 0x66, 0x7b, 0x40, 0x95, 0x89, 0x62, - 0xa8, 0x67, 0xe0, 0x3f, 0x3f, 0x16, 0x3a, 0x16, 0x57, 0xc4, 0x05, 0xdf, 0x91, 0x5c, 0xb0, 0x64, - 0x30, 0x73, 0xc1, 0xcf, 0x96, 0x4d, 0x49, 0x78, 0x04, 0xb6, 0xf3, 0x24, 0x5f, 0x15, 0x81, 0x32, - 0xa2, 0x0a, 0x94, 0x3d, 0x50, 0x39, 0x08, 0x83, 0x00, 0x7b, 0xac, 0x13, 0x99, 0x4b, 0xbc, 0xf5, - 0xc9, 0x4e, 0xa3, 0x2c, 0x32, 0x23, 0x2d, 0x9a, 0x09, 0xc7, 0x1d, 0x92, 0x99, 0xa6, 0xfe, 0x6e, - 0x26, 0x9c, 0xe5, 0x6b, 0x7d, 0xfe, 0x07, 0xcc, 0x72, 0x6c, 0xf8, 0x45, 0x01, 0x8b, 0xa3, 0x1e, - 0x85, 0x86, 0xa4, 0xea, 0x75, 0x6e, 0x57, 0x1f, 0x4c, 0x9e, 0x10, 0x9f, 0x8c, 0xb6, 0xf5, 0xe1, - 0xdb, 0xef, 0xd3, 0xa9, 0x0d, 0xb8, 0x1e, 0x2f, 0x18, 0xab, 0x4f, 0xac, 0x74, 0xc9, 0xd0, 0x51, - 0x9e, 0x8f, 0x0a, 0x00, 0x57, 0x2e, 0x86, 0x9b, 0x45, 0xdd, 0xc6, 0x76, 0x80, 0x7a, 0x6f, 0x92, - 0x50, 0x81, 0xb4, 0xc1, 0x91, 0xea, 0x70, 0x55, 0x82, 0x74, 0xe5, 0x7b, 0x78, 0xaa, 0x80, 0x4a, - 0xd6, 0xaa, 0x70, 0xab, 0xa8, 0x87, 0x64, 0x33, 0xa8, 0xf7, 0x27, 0x0b, 0x16, 0x48, 0x4d, 0x8e, - 0xa4, 0xc1, 0x86, 0x04, 0x29, 0xb7, 0x16, 0x38, 0x55, 0xd6, 0xe2, 0xc5, 0x54, 0x92, 0x25, 0x51, - 0x4c, 0x25, 0xdb, 0x1a, 0xd7, 0x52, 0xe5, 0xd6, 0x09, 0xfc, 0xa4, 0x80, 0x85, 0x9c, 0x49, 0x61, - 0x71, 0x27, 0x89, 0xd1, 0xd5, 0xed, 0x09, 0xa3, 0x05, 0xd8, 0x26, 0x07, 0x5b, 0x87, 0x6b, 0x32, - 0xb0, 0xdc, 0x4a, 0xe0, 0x64, 0x39, 0xcf, 0x16, 0x93, 0xc9, 0x8c, 0x5f, 0x4c, 0x26, 0x5d, 0x04, - 0xd7, 0x92, 0xe5, 0x8d, 0xdd, 0xde, 0x3d, 0xbb, 0xa8, 0x29, 0xe7, 0x17, 0x35, 0xe5, 0xd7, 0x45, - 0x4d, 0x39, 0xb9, 0xac, 0x95, 0xce, 0x2f, 0x6b, 0xa5, 0xef, 0x97, 0xb5, 0xd2, 0x9b, 0xbb, 0x8e, - 0xcb, 0xba, 0xa1, 0xa5, 0x1f, 0x90, 0x81, 0x31, 0x74, 0xd9, 0x7b, 0x97, 0xc5, 0xd5, 0xb6, 0x6d, - 0xb4, 0x3d, 0x20, 0x76, 0xd8, 0xc7, 0x06, 0x3b, 0xf6, 0x31, 0xb5, 0xe6, 0xf8, 0x62, 0x79, 0xf8, - 0x27, 0x00, 0x00, 0xff, 0xff, 0x10, 0x40, 0xa2, 0x74, 0x6b, 0x08, 0x00, 0x00, + // 803 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0x41, 0x6f, 0xeb, 0x44, + 0x10, 0xc7, 0xb3, 0x6d, 0xdf, 0x83, 0xb7, 0x49, 0x50, 0xbb, 0x54, 0xc5, 0x98, 0x36, 0x49, 0x1d, + 0x15, 0x52, 0x4a, 0x6d, 0x1a, 0x24, 0xce, 0x24, 0xa2, 0x2a, 0x17, 0x24, 0x70, 0x51, 0x91, 0x90, + 0x50, 0xb4, 0x8e, 0x17, 0xc7, 0x8a, 0xe3, 0x75, 0xbd, 0xeb, 0xd0, 0x5e, 0x39, 0x72, 0xaa, 0xd4, + 0x03, 0xe2, 0xca, 0x67, 0xe0, 0x23, 0x70, 0xe8, 0xb1, 0x12, 0x17, 0x4e, 0x80, 0x5a, 0x3e, 0x08, + 0xf2, 0x7a, 0xed, 0xda, 0x89, 0x5d, 0xe5, 0xdd, 0xe2, 0xfc, 0x67, 0x66, 0x7f, 0x33, 0xbb, 0xf3, + 0x87, 0x7b, 0xcc, 0x9e, 0x1a, 0x78, 0x8e, 0x5d, 0xcf, 0x98, 0x9f, 0x58, 0x84, 0xe3, 0x13, 0xe3, + 0x32, 0x22, 0xe1, 0xb5, 0x1e, 0x84, 0x94, 0x53, 0xb4, 0xc5, 0xec, 0xa9, 0x2e, 0x64, 0x5d, 0xca, + 0xea, 0xb6, 0x43, 0x1d, 0x2a, 0x54, 0x23, 0xfe, 0x95, 0x04, 0xaa, 0xbb, 0x0e, 0xa5, 0x8e, 0x47, + 0x0c, 0x1c, 0xb8, 0x06, 0xf6, 0x7d, 0xca, 0x31, 0x77, 0xa9, 0xcf, 0xa4, 0xba, 0xbf, 0x7c, 0xca, + 0x1c, 0x7b, 0xae, 0x8d, 0x39, 0x0d, 0x65, 0x48, 0x5b, 0x16, 0x10, 0x5f, 0x56, 0xf4, 0x83, 0xc1, + 0xdd, 0x19, 0x61, 0x1c, 0xcf, 0x02, 0x19, 0xa0, 0x2e, 0xd7, 0xe0, 0x57, 0x89, 0xa6, 0xb5, 0xe0, + 0xee, 0xd7, 0x31, 0xf5, 0x79, 0x64, 0xcd, 0x5c, 0x3e, 0xf4, 0xa8, 0x75, 0xce, 0x31, 0x8f, 0x98, + 0x49, 0x2e, 0x23, 0xc2, 0xb8, 0xf6, 0x07, 0x80, 0x7b, 0x15, 0x01, 0x2c, 0xa0, 0x3e, 0x23, 0x48, + 0x87, 0x2f, 0x42, 0xec, 0x3b, 0x44, 0x01, 0x1d, 0xd0, 0xab, 0xf7, 0x15, 0x7d, 0xa9, 0x71, 0xdd, + 0x8c, 0x75, 0x33, 0x09, 0x43, 0x3b, 0xf0, 0x25, 0x13, 0x15, 0x94, 0xb5, 0x0e, 0xe8, 0xbd, 0x32, + 0xe5, 0x17, 0xea, 0xc2, 0x66, 0x10, 0xd2, 0x39, 0xf1, 0x47, 0x13, 0xe2, 0x3a, 0x13, 0xae, 0xac, + 0x77, 0x40, 0x6f, 0xc3, 0x6c, 0x24, 0x7f, 0x7e, 0x21, 0xfe, 0x43, 0x9f, 0x42, 0xc5, 0xc3, 0x8c, + 0x8f, 0x2c, 0x8f, 0x5a, 0xa3, 0x39, 0xe5, 0xae, 0xef, 0x8c, 0x88, 0x6f, 0xb3, 0x11, 0xe6, 0xca, + 0x86, 0x88, 0xdf, 0x8e, 0xf5, 0x18, 0xf3, 0x42, 0xa8, 0xa7, 0xbe, 0xcd, 0x06, 0x5c, 0x53, 0xe0, + 0x8e, 0xe8, 0xe2, 0x22, 0x9d, 0x5d, 0xd6, 0xe0, 0xf7, 0xf0, 0x9d, 0x25, 0x45, 0x76, 0x36, 0x84, + 0x30, 0x9b, 0x35, 0x53, 0x40, 0x67, 0xbd, 0x57, 0xef, 0xef, 0x96, 0xb4, 0x97, 0xa5, 0x0e, 0x37, + 0xee, 0xfe, 0x6e, 0xd7, 0xcc, 0x5c, 0x96, 0x76, 0x06, 0x15, 0x51, 0x7e, 0x10, 0x67, 0x0c, 0x6c, + 0x3b, 0x24, 0x2c, 0x3d, 0x1a, 0x1d, 0xc1, 0xad, 0x2c, 0x72, 0x84, 0x13, 0x4d, 0x4c, 0xf1, 0x95, + 0xb9, 0x99, 0x09, 0x32, 0x47, 0xfb, 0x0c, 0xbe, 0x5b, 0x52, 0x48, 0x92, 0x76, 0x61, 0x53, 0x20, + 0x2d, 0x54, 0x69, 0xe0, 0x5c, 0xb0, 0xa6, 0x4a, 0x94, 0xaf, 0x72, 0x03, 0x4d, 0xa7, 0x90, 0x56, + 0x2f, 0x6a, 0x4f, 0xd5, 0x8b, 0x37, 0x03, 0x96, 0x6f, 0x46, 0x63, 0xf0, 0xed, 0xa1, 0x47, 0xc7, + 0xd3, 0x6f, 0x5d, 0x3e, 0x39, 0xbd, 0x0a, 0xdc, 0x50, 0x3c, 0xe3, 0xf8, 0xb6, 0x73, 0x49, 0xeb, + 0xa6, 0xfc, 0x42, 0x9f, 0x43, 0x48, 0xb2, 0x28, 0xf1, 0x12, 0xea, 0x7d, 0x55, 0x4f, 0x5e, 0xb2, + 0x9e, 0xbe, 0x64, 0xfd, 0x9b, 0xf4, 0x25, 0x0f, 0xdf, 0x8c, 0x27, 0x7b, 0xf3, 0x4f, 0x1b, 0x98, + 0xb9, 0x3c, 0xed, 0xbd, 0x14, 0x9b, 0xf8, 0xb6, 0xeb, 0x3b, 0x02, 0x20, 0xbb, 0xd9, 0x29, 0x54, + 0xcb, 0x44, 0xd9, 0xd4, 0x97, 0xf0, 0xad, 0x20, 0x11, 0xe2, 0xc7, 0x34, 0x9e, 0xa6, 0x17, 0xfc, + 0x7e, 0xc9, 0x05, 0x97, 0x34, 0x66, 0x36, 0x83, 0x7c, 0xd9, 0x8c, 0x44, 0x44, 0x10, 0xbb, 0x48, + 0xf2, 0x3b, 0x90, 0x28, 0x0b, 0xaa, 0x44, 0x39, 0x83, 0x8d, 0x71, 0x14, 0x86, 0xc4, 0xe7, 0xa3, + 0x78, 0x75, 0xe5, 0x22, 0xad, 0x36, 0x8d, 0xba, 0xcc, 0x8c, 0xb5, 0xb8, 0x27, 0x92, 0x9c, 0x90, + 0xf6, 0xb4, 0xf6, 0x7a, 0x3d, 0x91, 0x3c, 0x5f, 0xff, 0xd7, 0x37, 0xe0, 0x0b, 0x81, 0x8d, 0x7e, + 0x03, 0x70, 0x73, 0xd1, 0x00, 0x90, 0x51, 0x52, 0xf5, 0x39, 0x2f, 0x51, 0x3f, 0x5e, 0x3d, 0x21, + 0x99, 0x8c, 0x76, 0xf4, 0xd3, 0x9f, 0xff, 0xdd, 0xae, 0x1d, 0xa0, 0x6e, 0x62, 0x5f, 0xf1, 0xd6, + 0x67, 0x16, 0xc6, 0x16, 0x79, 0x7e, 0x06, 0x10, 0x3e, 0x6d, 0x31, 0x3a, 0xac, 0x3a, 0x6d, 0xc9, + 0x03, 0xd4, 0x0f, 0x57, 0x09, 0x95, 0x48, 0x07, 0x02, 0xa9, 0x8d, 0xf6, 0x4a, 0x90, 0x9e, 0xf6, + 0x1e, 0xdd, 0x02, 0xd8, 0xc8, 0xaf, 0x2a, 0x3a, 0xaa, 0x3a, 0xa3, 0xc4, 0x19, 0xd4, 0x8f, 0x56, + 0x0b, 0x96, 0x48, 0x3d, 0x81, 0xa4, 0xa1, 0x4e, 0x09, 0x52, 0xc1, 0x16, 0x04, 0x55, 0x7e, 0xc5, + 0xab, 0xa9, 0x4a, 0x4c, 0xa2, 0x9a, 0xaa, 0xcc, 0x35, 0x9e, 0xa5, 0x2a, 0xd8, 0x09, 0xfa, 0x05, + 0xc0, 0x66, 0x61, 0x49, 0x51, 0xf5, 0x49, 0x25, 0x8b, 0xae, 0x1e, 0xaf, 0x18, 0x2d, 0xc1, 0x0e, + 0x05, 0x58, 0x17, 0xed, 0x97, 0x81, 0x15, 0x2c, 0x41, 0x90, 0x15, 0x76, 0xb6, 0x9a, 0xac, 0x6c, + 0xf1, 0xab, 0xc9, 0x4a, 0x8d, 0xe0, 0x59, 0xb2, 0xe2, 0x62, 0x0f, 0x07, 0x77, 0x0f, 0x2d, 0x70, + 0xff, 0xd0, 0x02, 0xff, 0x3e, 0xb4, 0xc0, 0xcd, 0x63, 0xab, 0x76, 0xff, 0xd8, 0xaa, 0xfd, 0xf5, + 0xd8, 0xaa, 0x7d, 0xf7, 0x81, 0xe3, 0xf2, 0x49, 0x64, 0xe9, 0x63, 0x3a, 0x33, 0xe6, 0x2e, 0xff, + 0xd1, 0xe5, 0x49, 0xb5, 0x63, 0x1b, 0x1f, 0xcf, 0xa8, 0x1d, 0x79, 0xc4, 0xe0, 0xd7, 0x01, 0x61, + 0xd6, 0x4b, 0x61, 0x2c, 0x9f, 0xfc, 0x1f, 0x00, 0x00, 0xff, 0xff, 0x52, 0xce, 0x27, 0x0b, 0xc9, + 0x08, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -981,6 +1001,16 @@ func (m *QuerySubmitBlobStatusResponse) MarshalToSizedBuffer(dAtA []byte) (int, _ = i var l int _ = l + if m.LastBlobVotingEndsAt != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.LastBlobVotingEndsAt)) + i-- + dAtA[i] = 0x20 + } + if m.ProvenHeight != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.ProvenHeight)) + i-- + dAtA[i] = 0x18 + } if len(m.Status) > 0 { i -= len(m.Status) copy(dAtA[i:], m.Status) @@ -1372,6 +1402,12 @@ func (m *QuerySubmitBlobStatusResponse) Size() (n int) { if l > 0 { n += 1 + l + sovQuery(uint64(l)) } + if m.ProvenHeight != 0 { + n += 1 + sovQuery(uint64(m.ProvenHeight)) + } + if m.LastBlobVotingEndsAt != 0 { + n += 1 + sovQuery(uint64(m.LastBlobVotingEndsAt)) + } return n } @@ -1663,6 +1699,44 @@ func (m *QuerySubmitBlobStatusResponse) Unmarshal(dAtA []byte) error { } m.Status = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ProvenHeight", wireType) + } + m.ProvenHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ProvenHeight |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastBlobVotingEndsAt", wireType) + } + m.LastBlobVotingEndsAt = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastBlobVotingEndsAt |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) From 9a4cd8e7dfec8849783c5305fe7ecfd58d8e7e96 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Thu, 5 Sep 2024 15:18:35 +0530 Subject: [PATCH 40/58] remove deadcode --- chainclient/broadcast_tx.go | 25 ------------------------- keeper/abci.go | 3 ++- 2 files changed, 2 insertions(+), 26 deletions(-) diff --git a/chainclient/broadcast_tx.go b/chainclient/broadcast_tx.go index 7360c1a..4456d5f 100644 --- a/chainclient/broadcast_tx.go +++ b/chainclient/broadcast_tx.go @@ -47,28 +47,10 @@ func ExecuteTX(ctx sdk.Context, msg types.MsgUpdateBlobStatusRequest, cdc codec. return fmt.Errorf("error creating keyring: %w", err) } - // List all keys in the keyring - // keys, err := kr.List() - // if err != nil { - // fmt.Println("error listing keys:", err) - // } - info, err := kr.Key(keyName) valAddr, err := info.GetAddress() fmt.Println("after address................", valAddr) - // valAddr, err := sdk.AccAddressFromBech32(addr.String()) - // fmt.Println("val addr, err..", valAddr, err, addr) - - // fmt.Println("keysss........", keys) - - // // Print out the keys - // for _, keyInfo := range keys { - // addr, err := keyInfo.GetAddress() - // fmt.Println("err..", err) - // fmt.Printf("Name: %s, Address: %s\n", keyInfo.Name, addr) - // } - // Create an RPC client rpcClient, err := cometrpc.NewWithTimeout(rpcAddress, "/websocket", 3) if err != nil { @@ -78,12 +60,6 @@ func ExecuteTX(ctx sdk.Context, msg types.MsgUpdateBlobStatusRequest, cdc codec. // Create a new client context clientCtx := NewClientCtx(kr, rpcClient, ctx.ChainID(), cdc, homePath, valAddr) - // Retrieve the validator address (replace with actual logic to get the address) - // valAddr, err = sdk.AccAddressFromBech32("cosmos1fhqer4tc50nut2evvnj6yegcah2yfu3s844n9a") - // if err != nil { - // return fmt.Errorf("error parsing validator address: %w", err) - // } - // Set the client context's from fields clientCtx.FromName = keyName clientCtx.FromAddress = valAddr @@ -105,7 +81,6 @@ func ExecuteTX(ctx sdk.Context, msg types.MsgUpdateBlobStatusRequest, cdc codec. // Create a transaction factory and set the validator address in the message // factory := NewFactory(clientCtx) msg.ValidatorAddress = valAddr.String() - // time.Sleep(10 * time.Second) // Generate and broadcast the transaction if err := clitx.GenerateOrBroadcastTxWithFactory(clientCtx, factory, &msg); err != nil { diff --git a/keeper/abci.go b/keeper/abci.go index e728883..8db932f 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -162,7 +162,8 @@ func (h *ProofOfBlobProposalHandler) aggregateVotes(ctx sdk.Context, ci abci.Ext var totalStake int64 for _, v := range ci.Votes { - // TODO: why?? + // Process only votes with BlockIDFlagCommit, indicating the validator committed to the block. + // Skip votes with other flags (e.g., BlockIDFlagUnknown, BlockIDFlagNil). if v.BlockIdFlag != cmtproto.BlockIDFlagCommit { continue } From e7dbea94af98b2772ad5981c4ff5d93fc9e4d925 Mon Sep 17 00:00:00 2001 From: saiteja Date: Thu, 5 Sep 2024 17:38:41 +0530 Subject: [PATCH 41/58] feat: light client data verification --- keeper/abci.go | 2 +- keeper/keeper.go | 1 + keeper/store.go | 8 +++ .../{vote_entension.go => vote_extension.go} | 7 ++- keys.go | 2 + relayer/submit_data.go | 54 +++++++++++++++---- 6 files changed, 62 insertions(+), 12 deletions(-) rename keeper/{vote_entension.go => vote_extension.go} (91%) diff --git a/keeper/abci.go b/keeper/abci.go index b635664..5d69c61 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -83,7 +83,7 @@ func (h *ProofOfBlobProposalHandler) ProcessProposal(ctx sdk.Context, req *abci. } func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { - fmt.Println("coming hereee.........", ctx.BlockHeight()) + votingEndHeight := k.GetVotingEndHeightFromStore(ctx) blobStatus := k.GetBlobStatus(ctx) currentHeight := ctx.BlockHeight() diff --git a/keeper/keeper.go b/keeper/keeper.go index 9cb6061..467ce7b 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -124,6 +124,7 @@ func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatu newStatus = FAILURE_STATE } else { currentHeight := ctx.BlockHeight() + UpdateAvailHeight(ctx, store, req.AvailHeight) UpdateVotingEndHeight(ctx, store, uint64(currentHeight)+k.VotingInterval) } diff --git a/keeper/store.go b/keeper/store.go index dad583e..46065a6 100644 --- a/keeper/store.go +++ b/keeper/store.go @@ -76,6 +76,10 @@ func UpdateProvenHeight(ctx sdk.Context, store storetypes2.KVStore, provenHeight return updateHeight(store, availblob1.ProvenHeightKey, provenHeight) } +func UpdateAvailHeight(ctx sdk.Context, store storetypes2.KVStore, availHeight uint64) error { + return updateHeight(store, availblob1.AvailHeightKey, availHeight) +} + func UpdateVotingEndHeight(ctx sdk.Context, store storetypes2.KVStore, votingEndHeight uint64) error { return updateHeight(store, availblob1.VotingEndHeightKey, votingEndHeight) } @@ -93,6 +97,10 @@ func (k *Keeper) GetProvenHeightFromStore(ctx sdk.Context) uint64 { return k.getHeight(ctx, availblob1.ProvenHeightKey) } +func (k *Keeper) GetAvailHeightFromStore(ctx sdk.Context) uint64 { + return k.getHeight(ctx, availblob1.AvailHeightKey) +} + func (k *Keeper) GetVotingEndHeightFromStore(ctx sdk.Context) uint64 { return k.getHeight(ctx, availblob1.VotingEndHeightKey) } diff --git a/keeper/vote_entension.go b/keeper/vote_extension.go similarity index 91% rename from keeper/vote_entension.go rename to keeper/vote_extension.go index 20b31b4..20a732a 100644 --- a/keeper/vote_entension.go +++ b/keeper/vote_extension.go @@ -39,11 +39,12 @@ func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { - fmt.Println("coming to extend vote handler.........") // TODO: implement proper logic, this is for demo purpose only from := h.Keeper.GetStartHeightFromStore(ctx) end := h.Keeper.GetEndHeightFromStore(ctx) + availHeight := h.Keeper.GetAvailHeightFromStore(ctx) + pendingRangeKey := Key(from, end) blobStatus := h.Keeper.GetBlobStatus(ctx) @@ -67,6 +68,10 @@ func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { return abciResponseVoteExt, nil } + ok, err := h.Keeper.relayer.IsDataAvailable(from, end, availHeight, "http://localhost:8000") + fmt.Println("checking light client...", ok, err) + + // ok, checkLightClient() Votes[pendingRangeKey] = true voteExt := VoteExtension{ Votes: Votes, diff --git a/keys.go b/keys.go index d712512..d2d4220 100644 --- a/keys.go +++ b/keys.go @@ -36,6 +36,8 @@ var ( NextHeightKey = collections.NewPrefix(8) VotingEndHeightKey = collections.NewPrefix(9) + + AvailHeightKey = collections.NewPrefix(10) ) const ( diff --git a/relayer/submit_data.go b/relayer/submit_data.go index 94f05df..5ee9812 100644 --- a/relayer/submit_data.go +++ b/relayer/submit_data.go @@ -69,24 +69,58 @@ func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks return blockInfo, nil } -func (r *Relayer) GetSubmittedData(lightClientUrl string, blockNumber int) { +type BlockData struct { + Block int64 `json:"block_number"` + Extrinsics []interface{} `json:"data_transactions"` +} + +type ExtrinsicData struct { + Data string `json:"string"` +} + +func (r *Relayer) GetSubmittedData(lightClientUrl string, blockNumber int) (BlockData, error) { handler := NewHTTPClientHandler() - // get submitted block data using light client api with avail block height - // time.Sleep(20 * time.Second) // wait upto data to be submitted data to be included in the avail blocks - url := fmt.Sprintf("%s/v2/blocks/%v/data?feilds=data", lightClientUrl) - url = fmt.Sprintf(url, blockNumber) + // Construct the URL with the block number + url := fmt.Sprintf("%s/v2/blocks/%v/data?fields=data", lightClientUrl, blockNumber) + fmt.Println("get url.........", url) + // Perform the GET request, returning the body directly body, err := handler.Get(url) + + fmt.Println("body", blockNumber) if err != nil { - return + return BlockData{}, fmt.Errorf("failed to fetch data: %w", err) } - if body != nil { - r.logger.Info("submitted data to Avail verfied successfully at", - "block_height", blockNumber, - ) + // fmt.Println("blockkkkkk dataaaaaaa.....", string(body)) + + // Decode the response body into the BlockData struct + var blockData BlockData + err = json.Unmarshal(body, &blockData) + fmt.Println("hereee.......", err, blockData) + if err != nil { + return BlockData{}, fmt.Errorf("failed to decode response: %w", err) } + + // Log success + r.logger.Info("submitted data to Avail verified successfully at", + "block_height", blockNumber, + ) + + return blockData, nil +} + +func (r *Relayer) IsDataAvailable(from, to uint64, availHeight uint64, lightClientUrl string) (bool, error) { + fmt.Println("isDataAvailable................") + blockData, err := r.GetSubmittedData(lightClientUrl, int(availHeight)) + if err != nil { + fmt.Println("isDataAvailable.... error...", err) + return false, err + } + + fmt.Println("blockData.................", blockData) + return true, nil } // Define the struct that matches the JSON structure From b3d66312f53f9fa0dddf476cfed8e0367d17447d Mon Sep 17 00:00:00 2001 From: saiteja Date: Fri, 6 Sep 2024 11:46:18 +0530 Subject: [PATCH 42/58] feat: enable light client verification --- keeper/vote_extension.go | 2 +- relayer/publish.go | 26 ++++++++++++++++++-------- relayer/submit_data.go | 40 ++++++++++++++++++++++++++++------------ 3 files changed, 47 insertions(+), 21 deletions(-) diff --git a/keeper/vote_extension.go b/keeper/vote_extension.go index 20a732a..69d4adf 100644 --- a/keeper/vote_extension.go +++ b/keeper/vote_extension.go @@ -68,7 +68,7 @@ func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { return abciResponseVoteExt, nil } - ok, err := h.Keeper.relayer.IsDataAvailable(from, end, availHeight, "http://localhost:8000") + ok, err := h.Keeper.relayer.IsDataAvailable(ctx, from, end, availHeight, "http://localhost:8000") fmt.Println("checking light client...", ok, err) // ok, checkLightClient() diff --git a/relayer/publish.go b/relayer/publish.go index 87ec3d8..685982a 100644 --- a/relayer/publish.go +++ b/relayer/publish.go @@ -61,12 +61,9 @@ func (r *Relayer) PostBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo go r.postBlocks(ctx, blocks, cdc, proposer) } -// postBlocks will publish rollchain blocks to avail -// start height is inclusive, end height is exclusive -func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCodec, proposer []byte) { - // process blocks instead of random data +func (r *Relayer) GetBlocksDataFromLocal(ctx sdk.Context, blocks []int64) []byte { if len(blocks) == 0 { - return + return []byte{} } var bb []byte @@ -75,24 +72,37 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo res, err := r.localProvider.GetBlockAtHeight(ctx, height) if err != nil { r.logger.Error("Error getting block", "height:", height, "error", err) - return + return []byte{} } blockProto, err := res.Block.ToProto() if err != nil { r.logger.Error("Error protoing block", "error", err) - return + return []byte{} } blockBz, err := blockProto.Marshal() if err != nil { r.logger.Error("Error marshaling block", "error", err) - return + return []byte{} } bb = append(bb, blockBz...) } + return bb +} + +// postBlocks will publish rollchain blocks to avail +// start height is inclusive, end height is exclusive +func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCodec, proposer []byte) { + // process blocks instead of random data + if len(blocks) == 0 { + return + } + + bb := r.GetBlocksDataFromLocal(ctx, blocks) + fmt.Println("is it coming here where we post to DA") blockInfo, err := r.SubmitDataToClient(r.rpcClient.config.Seed, r.rpcClient.config.AppID, bb, blocks, r.rpcClient.config.LightClientURL) diff --git a/relayer/submit_data.go b/relayer/submit_data.go index 5ee9812..9db08ae 100644 --- a/relayer/submit_data.go +++ b/relayer/submit_data.go @@ -14,6 +14,7 @@ import ( "github.com/centrifuge/go-substrate-rpc-client/v4/registry/state" "github.com/centrifuge/go-substrate-rpc-client/v4/signature" "github.com/centrifuge/go-substrate-rpc-client/v4/types" + sdk "github.com/cosmos/cosmos-sdk/types" ) func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks []int64, lightClientUrl string) (BlockInfo, error) { @@ -70,12 +71,12 @@ func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks } type BlockData struct { - Block int64 `json:"block_number"` - Extrinsics []interface{} `json:"data_transactions"` + Block int64 `json:"block_number"` + Extrinsics []ExtrinsicData `json:"data_transactions"` } type ExtrinsicData struct { - Data string `json:"string"` + Data string `json:"data"` } func (r *Relayer) GetSubmittedData(lightClientUrl string, blockNumber int) (BlockData, error) { @@ -93,12 +94,9 @@ func (r *Relayer) GetSubmittedData(lightClientUrl string, blockNumber int) (Bloc return BlockData{}, fmt.Errorf("failed to fetch data: %w", err) } - // fmt.Println("blockkkkkk dataaaaaaa.....", string(body)) - // Decode the response body into the BlockData struct var blockData BlockData err = json.Unmarshal(body, &blockData) - fmt.Println("hereee.......", err, blockData) if err != nil { return BlockData{}, fmt.Errorf("failed to decode response: %w", err) } @@ -111,16 +109,34 @@ func (r *Relayer) GetSubmittedData(lightClientUrl string, blockNumber int) (Bloc return blockData, nil } -func (r *Relayer) IsDataAvailable(from, to uint64, availHeight uint64, lightClientUrl string) (bool, error) { - fmt.Println("isDataAvailable................") - blockData, err := r.GetSubmittedData(lightClientUrl, int(availHeight)) +// query the avail light client and check if the data is made available at the given height +func (r *Relayer) IsDataAvailable(ctx sdk.Context, from, to uint64, availHeight uint64, lightClientUrl string) (bool, error) { + availBlock, err := r.GetSubmittedData(lightClientUrl, int(availHeight)) if err != nil { - fmt.Println("isDataAvailable.... error...", err) return false, err } - fmt.Println("blockData.................", blockData) - return true, nil + var blocks []int64 + for i := from; i <= to; i++ { + blocks = append(blocks, int64(i)) + } + + cosmosBlocksData := r.GetBlocksDataFromLocal(ctx, blocks) + base64CosmosBlockData := base64.StdEncoding.EncodeToString(cosmosBlocksData) + + // TODO: any better / optimized way to check if data is really available? + return isDataIncludedInBlock(availBlock, base64CosmosBlockData), nil +} + +// bruteforce comparision check +func isDataIncludedInBlock(availBlock BlockData, base64cosmosData string) bool { + for _, data := range availBlock.Extrinsics { + if data.Data == base64cosmosData { + return true + } + } + + return false } // Define the struct that matches the JSON structure From 1d8b3a1926e1b9c16520a41c4540ad3023d74254 Mon Sep 17 00:00:00 2001 From: PrathyushaLakkireddy Date: Fri, 6 Sep 2024 13:10:12 +0530 Subject: [PATCH 43/58] fix --- keeper/abci.go | 7 ++--- keeper/keeper.go | 10 +++--- keeper/preblocker_handle.go | 37 ---------------------- keeper/vote_extension.go | 7 ++++- keys.go | 5 +-- relayer/publish.go | 5 ++- relayer/submit_data.go | 62 ++++++------------------------------- relayer/types.go | 10 ++++++ 8 files changed, 34 insertions(+), 109 deletions(-) delete mode 100644 keeper/preblocker_handle.go create mode 100644 relayer/types.go diff --git a/keeper/abci.go b/keeper/abci.go index 9d66712..22ab009 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -51,9 +51,6 @@ func (h *ProofOfBlobProposalHandler) PrepareProposal(ctx sdk.Context, req *abci. Votes: votes, ExtendedCommitInfo: req.LocalLastCommit, } - - fmt.Println("votes..................", votes) - bz, err := json.Marshal(injectedVoteExtTx) if err != nil { fmt.Println("failed to encode injected vote extension tx", "err", err) @@ -99,7 +96,7 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err pendingRangeKey := Key(from, to) votingPower := injectedVoteExtTx.Votes[pendingRangeKey] - if votingPower > 0 { + if votingPower > 0 { // TODO: calculate voting power properly k.setBlobStatusSuccess(ctx) } else { k.SetBlobStatusFailure(ctx) @@ -113,7 +110,7 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err } provenHeight := k.GetProvenHeightFromStore(ctx) - fromHeight := provenHeight + 1 + fromHeight := provenHeight + 1 // Calcualte pending range of blocks to post data endHeight := min(fromHeight+uint64(k.MaxBlocksForBlob), uint64(ctx.BlockHeight())) //exclusive i.e [fromHeight, endHeight) sdkCtx := sdk.UnwrapSDKContext(ctx) diff --git a/keeper/keeper.go b/keeper/keeper.go index 467ce7b..23c7ff0 100644 --- a/keeper/keeper.go +++ b/keeper/keeper.go @@ -55,7 +55,6 @@ func NewKeeper( cdc codec.BinaryCodec, appOpts servertypes.AppOptions, storeService storetypes.KVStoreService, - // sk *stakingkeeper.Keeper, uk *upgradekeeper.Keeper, key storetypes2.StoreKey, publishToAvailBlockInterval int, @@ -65,7 +64,6 @@ func NewKeeper( sb := collections.NewSchemaBuilder(storeService) return &Keeper{ - // stakingKeeper: sk, upgradeKeeper: uk, Validators: collections.NewMap(sb, availblob1.ValidatorsKey, "validators", collections.StringKey, collections.StringValue), @@ -104,7 +102,7 @@ func (k *Keeper) SubmitBlob(ctx sdk.Context, req *types.MsgSubmitBlobRequest) (* } func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatusRequest) (*types.MsgUpdateBlobStatusResponse, error) { - //Todo: status should be changed to Voting or Ready, depending on the request + // status should be changed to Voting or Ready, depending on the request store := ctx.KVStore(k.storeKey) provenHeight := k.GetProvenHeightFromStore(ctx) endHeight := k.GetEndHeightFromStore(ctx) @@ -124,11 +122,11 @@ func (k *Keeper) UpdateBlobStatus(ctx sdk.Context, req *types.MsgUpdateBlobStatu newStatus = FAILURE_STATE } else { currentHeight := ctx.BlockHeight() - UpdateAvailHeight(ctx, store, req.AvailHeight) - UpdateVotingEndHeight(ctx, store, uint64(currentHeight)+k.VotingInterval) + UpdateAvailHeight(ctx, store, req.AvailHeight) // updates avail height at which the blocks got submitted to DA + UpdateVotingEndHeight(ctx, store, uint64(currentHeight)+k.VotingInterval) // TODO: Now voting interval is 5, so check whether we can process votes at next block after tx exec. } - UpdateBlobStatus(ctx, store, newStatus) + UpdateBlobStatus(ctx, store, newStatus) // updates blob status after based on tx exec return &types.MsgUpdateBlobStatusResponse{}, nil } diff --git a/keeper/preblocker_handle.go b/keeper/preblocker_handle.go deleted file mode 100644 index e5891a8..0000000 --- a/keeper/preblocker_handle.go +++ /dev/null @@ -1,37 +0,0 @@ -package keeper - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/vitwit/avail-da-module/types" -) - -func (k *Keeper) preblockerPendingBlocks(ctx sdk.Context, blockTime time.Time, proposerAddr []byte, pendingBlocks *types.PendingBlocks) error { - // if pendingBlocks != nil { - // if reflect.DeepEqual(k.proposerAddress, proposerAddr) { - // k.relayer.PostBlocks(ctx, pendingBlocks.BlockHeights, k.cdc, proposerAddr) - // } - - // for _, pendingBlock := range pendingBlocks.BlockHeights { - // if err := k.AddUpdatePendingBlock(ctx, pendingBlock, blockTime); err != nil { - // return fmt.Errorf("preblocker pending blocks, %v", err) - // } - // } - // } - - return nil -} - -func (k *Keeper) notifyProvenHeight(ctx sdk.Context, previousProvenHeight int64) { - - // TODO - // provenHeight, err := k.GetProvenHeight(ctx) - // if err != nil { - // fmt.Println("unable to get proven height", err) - // return - // } - - // //k.relayer.NotifyProvenHeight(provenHeight) - // go k.relayer.PruneBlockStore(previousProvenHeight) -} diff --git a/keeper/vote_extension.go b/keeper/vote_extension.go index 69d4adf..580da96 100644 --- a/keeper/vote_extension.go +++ b/keeper/vote_extension.go @@ -70,9 +70,14 @@ func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { ok, err := h.Keeper.relayer.IsDataAvailable(ctx, from, end, availHeight, "http://localhost:8000") fmt.Println("checking light client...", ok, err) + if ok { + h.logger.Info("submitted data to Avail verified successfully at", + "block_height", availHeight, + ) + } // ok, checkLightClient() - Votes[pendingRangeKey] = true + Votes[pendingRangeKey] = ok voteExt := VoteExtension{ Votes: Votes, } diff --git a/keys.go b/keys.go index d2d4220..0eaa2e3 100644 --- a/keys.go +++ b/keys.go @@ -42,7 +42,7 @@ var ( const ( // ModuleName is the name of the module - ModuleName = "availdamodule" + ModuleName = "cada" // StoreKey to be used when creating the KVStore StoreKey = ModuleName @@ -52,9 +52,6 @@ const ( // QuerierRoute to be used for querier msgs QuerierRoute = ModuleName - - // TransientStoreKey defines the transient store key - TransientStoreKey = "transient_" + ModuleName ) func PendingBlobsStoreKey(blocksRange types.Range) []byte { diff --git a/relayer/publish.go b/relayer/publish.go index 148f38b..b6d5412 100644 --- a/relayer/publish.go +++ b/relayer/publish.go @@ -101,9 +101,8 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo fmt.Println("is it coming here where we post to DA") - blockInfo, err := r.SubmitDataToClient(r.rpcClient.config.Seed, r.rpcClient.config.AppID, bb, blocks, r.rpcClient.config.LightClientURL) + blockInfo, err := r.SubmitDataToAvailClient(r.rpcClient.config.Seed, r.rpcClient.config.AppID, bb, blocks, r.rpcClient.config.LightClientURL) - fmt.Println("after submission.............", err) if err != nil { r.logger.Error("Error while submitting block(s) to Avail DA", "height_start", blocks[0], @@ -111,7 +110,7 @@ func (r *Relayer) postBlocks(ctx sdk.Context, blocks []int64, cdc codec.BinaryCo "appID", string(r.rpcClient.config.AppID), ) - // TODO : execute tx about failure submission + // execute tx about failure submission err = dacli.ExecuteTX(ctx, types.MsgUpdateBlobStatusRequest{ ValidatorAddress: sdk.AccAddress.String(proposer), BlocksRange: &types.Range{ diff --git a/relayer/submit_data.go b/relayer/submit_data.go index 9db08ae..0f6e6c3 100644 --- a/relayer/submit_data.go +++ b/relayer/submit_data.go @@ -1,9 +1,7 @@ package relayer import ( - "crypto/rand" "encoding/base64" - "encoding/hex" "encoding/json" "fmt" "time" @@ -17,24 +15,20 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks []int64, lightClientUrl string) (BlockInfo, error) { - fmt.Println("calling twiceeeee.........", blocks) +func (r *Relayer) SubmitDataToAvailClient(Seed string, AppID int, data []byte, blocks []int64, lightClientUrl string) (BlockInfo, error) { var blockInfo BlockInfo // if r.submittedBlocksCache[blocks[0]] { // return blockInfo, nil // } - // r.submittedBlocksCache[blocks[0]] = true - delete(r.submittedBlocksCache, blocks[0]-int64(len(blocks))) + // // r.submittedBlocksCache[blocks[0]] = true + // delete(r.submittedBlocksCache, blocks[0]-int64(len(blocks))) handler := NewHTTPClientHandler() datab := base64.StdEncoding.EncodeToString(data) jsonData := []byte(fmt.Sprintf(`{"data":"%s"}`, datab)) - // Define the URL - //url := "http://127.0.0.1:8000/v2/submit" - url := fmt.Sprintf("%s/v2/submit", lightClientUrl) // Make the POST request @@ -44,8 +38,6 @@ func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks return blockInfo, err } - // Create an instance of the struct - // Unmarshal the JSON data into the struct err = json.Unmarshal(responseBody, &blockInfo) if err != nil { @@ -70,46 +62,29 @@ func (r *Relayer) SubmitDataToClient(Seed string, AppID int, data []byte, blocks return blockInfo, nil } -type BlockData struct { - Block int64 `json:"block_number"` - Extrinsics []ExtrinsicData `json:"data_transactions"` -} - -type ExtrinsicData struct { - Data string `json:"data"` -} - func (r *Relayer) GetSubmittedData(lightClientUrl string, blockNumber int) (BlockData, error) { handler := NewHTTPClientHandler() // Construct the URL with the block number url := fmt.Sprintf("%s/v2/blocks/%v/data?fields=data", lightClientUrl, blockNumber) - fmt.Println("get url.........", url) // Perform the GET request, returning the body directly body, err := handler.Get(url) - - fmt.Println("body", blockNumber) if err != nil { - return BlockData{}, fmt.Errorf("failed to fetch data: %w", err) + return BlockData{}, fmt.Errorf("failed to fetch data from the avail: %w", err) } // Decode the response body into the BlockData struct var blockData BlockData err = json.Unmarshal(body, &blockData) if err != nil { - return BlockData{}, fmt.Errorf("failed to decode response: %w", err) + return BlockData{}, fmt.Errorf("failed to decode block response: %w", err) } - // Log success - r.logger.Info("submitted data to Avail verified successfully at", - "block_height", blockNumber, - ) - return blockData, nil } -// query the avail light client and check if the data is made available at the given height +// IsDataAvailable is to query the avail light client and check if the data is made available at the given height func (r *Relayer) IsDataAvailable(ctx sdk.Context, from, to uint64, availHeight uint64, lightClientUrl string) (bool, error) { availBlock, err := r.GetSubmittedData(lightClientUrl, int(availHeight)) if err != nil { @@ -146,7 +121,7 @@ type GetBlock struct { } // submitData creates a transaction and makes a Avail data submission -func (r *Relayer) SubmitData1(ApiURL string, Seed string, AppID int, data []byte, blocks []int64) error { +func (r *Relayer) SubmitDataToAvailDA(ApiURL string, Seed string, AppID int, data []byte, blocks []int64) error { api, err := gsrpc.NewSubstrateAPI(ApiURL) if err != nil { r.logger.Error("cannot create api:%w", err) @@ -198,8 +173,6 @@ func (r *Relayer) SubmitData1(ApiURL string, Seed string, AppID int, data []byte return err } - // fmt.Println("keyring pair", keyringPair) - key, err := types.CreateStorageKey(meta, "System", "Account", keyringPair.PublicKey) if err != nil { r.logger.Error("cannot create storage key:%w", err) @@ -351,7 +324,7 @@ func (r *Relayer) SubmitData1(ApiURL string, Seed string, AppID int, data []byte } fmt.Printf("Txn inside finalized block\n") hash := status.AsFinalized - err = getData1(hash, api, string(data)) + err = GetDataFromAvailDA(hash, api, string(data)) if err != nil { r.logger.Error("cannot get data:%v", err) return err @@ -365,29 +338,12 @@ func (r *Relayer) SubmitData1(ApiURL string, Seed string, AppID int, data []byte } } -// RandToken generates a random hex value. -func RandToken1(n int) (string, error) { - bytes := make([]byte, n) - if _, err := rand.Read(bytes); err != nil { - return "", err - } - return hex.EncodeToString(bytes), nil -} - -func getData1(hash types.Hash, api *gsrpc.SubstrateAPI, data string) error { - +func GetDataFromAvailDA(hash types.Hash, api *gsrpc.SubstrateAPI, data string) error { block, err := api.RPC.Chain.GetBlock(hash) if err != nil { return fmt.Errorf("cannot get block by hash:%w", err) } - // Encode the struct to JSON - // jsonData, err := json.Marshal(block.Block.Header) - // if err != nil { - // log.Fatal(err) - // } - - // fmt.Println("length of extrinsics: ", len(block.Block.Extrinsics)) for _, ext := range block.Block.Extrinsics { // these values below are specific indexes only for data submission, differs with each extrinsic diff --git a/relayer/types.go b/relayer/types.go new file mode 100644 index 0000000..3e8b432 --- /dev/null +++ b/relayer/types.go @@ -0,0 +1,10 @@ +package relayer + +type BlockData struct { + Block int64 `json:"block_number"` + Extrinsics []ExtrinsicData `json:"data_transactions"` +} + +type ExtrinsicData struct { + Data string `json:"data"` +} From ff46ba2c378a6ca6d992eb5b3b7b3b1bb52a7fec Mon Sep 17 00:00:00 2001 From: saiteja Date: Tue, 10 Sep 2024 12:39:09 +0530 Subject: [PATCH 44/58] docs: add specs --- specs/README.md | 90 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 specs/README.md diff --git a/specs/README.md b/specs/README.md new file mode 100644 index 0000000..7cc44b8 --- /dev/null +++ b/specs/README.md @@ -0,0 +1,90 @@ + +# `x/cada` + + + +### MaxBlocksLimitForBlob + +* The `maxBlocksLimitForBlob` defines the maximum number blobs to be posted to Avail DA at once (in on Avail Transaction). + +### Blob Interval +* The `Blob Interval` defines the frequency at which block data is posted to the Avail Network. +* For example, if the interval is set to `5`, data will be submitted at block heights `6`, `11`, `16`, and so on. +* At each of these intervals, the block data from the proven height to min(current height, proven height + maxBlocksLimitForBlob) will be posted. + +Example: +For Blob Interval = 5 and Maximum Blocks Limit for Blob = 10 :- + +- At height `6` and provenHeight = `0`, blocks from `1` to `5` are posted. + +- At height `11` and provenHeight still `0`, blocks from `1` to `10` are posted. + +### Relayer +* The `Relayer` acts as the transport layer, responsible for handling requests from the `prepareBlocker` and facilitating transactions between the Cosmos chain and the Avail DA network. +* It performs key functions such as submitting block data to Avail and updating block status on the Cosmos chain. Every validator in the network is required to run the relayer process. +* Relayer should initialized with a chain account so that the validator can use this account to sign `MsgUpdateStatusBlob` transaction. + +### Voting Interval +* The `Voting Interval` is the period before validators verify whether data is truly included in Avail and confirm it with the network using vote extensions. + + +## State + +The module keeps state of the following primary objects: + +1. **Blocks Height Range**: Tracks the start and end of the current blocks range being posted to Avail. +2. **Blob Submission Status**: Indicates the current status of the blob submission process (`READY`, `PENDING`, `IN_VOTING`, `FAILURE`). +3. **Voting End Height**: The block height at which the voting for the current blocks should conclude. +4. **Avail Height**: The Avail block height at which the data is made available. +5. **Proven Height**: The latest block height of the Cosmos chain for which data has been successfully posted to Avail and verified by the network. + +The module uses the following keys to manage the aforementioned state: + +* **Height Range Start Key**: `0x07` - Stores the start of the range of current blocks being posted to Avail. +* **Height Range End Key**: `0x08` - Stores the end of the range of current blocks being posted to Avail. +* **Blob Status Key**: `0x06` - Stores the status of the blob submission process. +* **Voting End Height Key**: `0x09` - Stores the block height at which voting should end for the current blocks. +* **Avail Height Key**: `0x0A` - Stores the Avail block height where the data is made available. + + + +## Architecture + + + - At each block interval, a request is sent from the `PreBlocker` ABCI method to the Keeper, specifying the range of block heights that are ready to be posted to the `Avail` DA network. + - The range of block heights should be from `provenHeight + 1` to `min(provenHeight + MaxBlocksLimitForBlob, CurrentBlockHeight)`. + + - If the status of the previous blocks is either `READY` or `FAILURE`, the status can be updated to `PENDING`. + + ``` + range = [fromBlock, toBlock] // (fromBlock < toBlock < CurrentBlock) + status = PENDING + ``` + + - The `Proposer` of the block will make a request to the `Relayer` to post the blocks data by passing the range of blocks to be posted. + + - The `Relayer` fetches the blocks data from the local provider, converts the blocks data to bytes, and posts that data to `Avail`. + + - Once the success of data availability is confirmed, the `Relayer` broadcasts the `Avail height` at which the blob data is made available using the `MsgUpdateBlobStatus` transaction. + + - The status, Avail height, and voting deadline will be updated in the state. + + ``` + status = IN_VOTING + availHeight = tx.availHeight + votingEndBlock = currentBlock + votingInterval + ``` + + - At block height `VotingEndBlock - 1`, all the validators verify if the specified blocks data is truly made available at the specified Avail height. They cast their vote (YES or NO) using `vote extensions`. + + - At block height `VotingEndBlock`, all the votes from `vote_extensions` will be collected and aggregated. If the collective `voting power is > 66%`, the status will be updated + + ``` + status = READY // success and ready for next blocks + provenHeight = Range End + + ``` + - In case of failure at any stage, the whole flow will be repeated. + + +--- From f66f82576d0119474c4e8e6970c961c85027dec8 Mon Sep 17 00:00:00 2001 From: saiteja Date: Tue, 10 Sep 2024 12:43:14 +0530 Subject: [PATCH 45/58] feat: docs: add abstract --- specs/README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/specs/README.md b/specs/README.md index 7cc44b8..d50588e 100644 --- a/specs/README.md +++ b/specs/README.md @@ -2,6 +2,13 @@ # `x/cada` +## Abstract + +This document specifies the bank module of the Cosmos SDK. + +CADA is a module designed to connect Cosmos sovereign chains with the Avail network, making it easier for any Cosmos chain or rollapp to use Avail as their Data Availability (DA) layer. With CADA, developers can improve the scalability and security of their decentralized applications within the Cosmos ecosystem. It enables better data handling and availability, allowing Cosmos-based chains to tap into the strengths of Avail and build a more connected and resilient blockchain network. + + ### MaxBlocksLimitForBlob From 7700b262f60648c0247e1bedf20808510417af04 Mon Sep 17 00:00:00 2001 From: Teja2045 <106052623+Teja2045@users.noreply.github.com> Date: Tue, 10 Sep 2024 12:44:24 +0530 Subject: [PATCH 46/58] Update README.md --- specs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specs/README.md b/specs/README.md index d50588e..3a6aa4d 100644 --- a/specs/README.md +++ b/specs/README.md @@ -4,7 +4,7 @@ ## Abstract -This document specifies the bank module of the Cosmos SDK. +This document specifies the cada module of the Cosmos SDK. CADA is a module designed to connect Cosmos sovereign chains with the Avail network, making it easier for any Cosmos chain or rollapp to use Avail as their Data Availability (DA) layer. With CADA, developers can improve the scalability and security of their decentralized applications within the Cosmos ecosystem. It enables better data handling and availability, allowing Cosmos-based chains to tap into the strengths of Avail and build a more connected and resilient blockchain network. From 27819f6d8e360122033422d9f531976a566c0438 Mon Sep 17 00:00:00 2001 From: saiteja Date: Tue, 10 Sep 2024 16:16:54 +0530 Subject: [PATCH 47/58] feat: add specs --- specs/01_concepts.md | 32 ++++++++++++++++++++++ specs/02_state.md | 64 ++++++++++++++++++++++++++++++++++++++++++++ specs/03_msg.md | 3 +++ specs/README.md | 44 ------------------------------ 4 files changed, 99 insertions(+), 44 deletions(-) create mode 100644 specs/01_concepts.md create mode 100644 specs/02_state.md create mode 100644 specs/03_msg.md diff --git a/specs/01_concepts.md b/specs/01_concepts.md new file mode 100644 index 0000000..59b0352 --- /dev/null +++ b/specs/01_concepts.md @@ -0,0 +1,32 @@ + + +# Concepts + +### MaxBlocksLimitForBlob + +- The `maxBlocksLimitForBlob` defines the maximum number blobs to be posted to Avail DA at once (in on Avail Transaction). + +### Blob Interval + +- The `Blob Interval` defines the frequency at which block data is posted to the Avail Network. +- For example, if the interval is set to `5`, data will be submitted at block heights `6`, `11`, `16`, and so on. +- At each of these intervals, the block data from the proven height to min(current height, proven height + maxBlocksLimitForBlob) will be posted. + +Example: +For Blob Interval = 5 and Maximum Blocks Limit for Blob = 10 :- + +- At height `6` and provenHeight = `0`, blocks from `1` to `5` are posted. + +- At height `11` and provenHeight still `0`, blocks from `1` to `10` are posted. + +### Relayer + +- The `Relayer` acts as the transport layer, responsible for handling requests from the `prepareBlocker` and facilitating transactions between the Cosmos chain and the Avail DA network. +- It performs key functions such as submitting block data to Avail and updating block status on the Cosmos chain. Every validator in the network is required to run the relayer process. +- Relayer should initialized with a chain account so that the validator can use this account to sign `MsgUpdateStatusBlob` transaction. + +### Voting Interval + +- The `Voting Interval` is the period before validators verify whether data is truly included in Avail and confirm it with the network using vote extensions. diff --git a/specs/02_state.md b/specs/02_state.md new file mode 100644 index 0000000..78ec24e --- /dev/null +++ b/specs/02_state.md @@ -0,0 +1,64 @@ + + +# State + +The module keeps state of the following primary objects: + +## Blocks Range + +Tracks the start and end of the current blocks range being posted to `Avail`. + +### Blocks Range Start Height + +Stores the start height of the range of current blocks being posted to `Avail`. + +It is stored in the state as follows: + +- PrevHeightKey `0x07` -> Start Height (Uint64) + +### Blocks Range End Height + +Stores the end height of the range of current blocks being posted to `Avail`. + +It is stored in the state as follows: + +- NextHeightKey `0x08` -> End Height (Uint64) + +## Blocks Submission Status + +Indicates the status of the current blocks submission (`READY`, `PENDING`, `IN_VOTING`, `FAILURE`). + +** PENDING ** : Blocks data submission has been initiated and is awaiting confirmation +** IN_VOTING ** : Blocks data has been posted to `Avail` and is now pending validators' verification +** FAILURE ** : Blocks data submission or verification has failed and needs to be resubmitted +** READY ** : blocks data submission is successful; the next set of blocks is ready to be posted + +It is stored in the state as follows: + +- BlobStatusKey `0x06` : status (uint32) + +## Voting End Height + +The block height at which the voting for the current blocks should conclude. + +It is stored in the state as follows: + +- VotingEndHeightKey `0x09` : voting end block height (uint64) + +## Avail Height + +The Avail block height at which the data is made available. + +It is stored in the state as follows: + +AvailHeightKey `0x0A` : avail block height (uint64) + +## Proven Height + +The latest block height of the Cosmos chain for which data has been successfully posted to Avail and verified by the network. + +It is stored in the state as follows: + +ProvenHeightKey `0x02` : proven block height (uint64) diff --git a/specs/03_msg.md b/specs/03_msg.md new file mode 100644 index 0000000..6125f63 --- /dev/null +++ b/specs/03_msg.md @@ -0,0 +1,3 @@ +# Messages + +## \ No newline at end of file diff --git a/specs/README.md b/specs/README.md index d50588e..8c1f798 100644 --- a/specs/README.md +++ b/specs/README.md @@ -10,50 +10,6 @@ CADA is a module designed to connect Cosmos sovereign chains with the Avail netw -### MaxBlocksLimitForBlob - -* The `maxBlocksLimitForBlob` defines the maximum number blobs to be posted to Avail DA at once (in on Avail Transaction). - -### Blob Interval -* The `Blob Interval` defines the frequency at which block data is posted to the Avail Network. -* For example, if the interval is set to `5`, data will be submitted at block heights `6`, `11`, `16`, and so on. -* At each of these intervals, the block data from the proven height to min(current height, proven height + maxBlocksLimitForBlob) will be posted. - -Example: -For Blob Interval = 5 and Maximum Blocks Limit for Blob = 10 :- - -- At height `6` and provenHeight = `0`, blocks from `1` to `5` are posted. - -- At height `11` and provenHeight still `0`, blocks from `1` to `10` are posted. - -### Relayer -* The `Relayer` acts as the transport layer, responsible for handling requests from the `prepareBlocker` and facilitating transactions between the Cosmos chain and the Avail DA network. -* It performs key functions such as submitting block data to Avail and updating block status on the Cosmos chain. Every validator in the network is required to run the relayer process. -* Relayer should initialized with a chain account so that the validator can use this account to sign `MsgUpdateStatusBlob` transaction. - -### Voting Interval -* The `Voting Interval` is the period before validators verify whether data is truly included in Avail and confirm it with the network using vote extensions. - - -## State - -The module keeps state of the following primary objects: - -1. **Blocks Height Range**: Tracks the start and end of the current blocks range being posted to Avail. -2. **Blob Submission Status**: Indicates the current status of the blob submission process (`READY`, `PENDING`, `IN_VOTING`, `FAILURE`). -3. **Voting End Height**: The block height at which the voting for the current blocks should conclude. -4. **Avail Height**: The Avail block height at which the data is made available. -5. **Proven Height**: The latest block height of the Cosmos chain for which data has been successfully posted to Avail and verified by the network. - -The module uses the following keys to manage the aforementioned state: - -* **Height Range Start Key**: `0x07` - Stores the start of the range of current blocks being posted to Avail. -* **Height Range End Key**: `0x08` - Stores the end of the range of current blocks being posted to Avail. -* **Blob Status Key**: `0x06` - Stores the status of the blob submission process. -* **Voting End Height Key**: `0x09` - Stores the block height at which voting should end for the current blocks. -* **Avail Height Key**: `0x0A` - Stores the Avail block height where the data is made available. - - ## Architecture From e12dc8b5ffe02ea37931233b81e885fa6a3bf433 Mon Sep 17 00:00:00 2001 From: saiteja Date: Wed, 11 Sep 2024 14:54:51 +0530 Subject: [PATCH 48/58] feat: spec --- keeper/abci.go | 3 ++ specs/02_state.md | 2 +- specs/03_msg.md | 13 +++++- specs/04_client.md | 35 +++++++++++++++ specs/05_prepare_proposal.md | 59 +++++++++++++++++++++++++ specs/06_preblocker.md | 83 ++++++++++++++++++++++++++++++++++++ specs/07_vote_extension.md | 79 ++++++++++++++++++++++++++++++++++ specs/README.md | 11 +++++ 8 files changed, 283 insertions(+), 2 deletions(-) create mode 100644 specs/04_client.md create mode 100644 specs/05_prepare_proposal.md create mode 100644 specs/06_preblocker.md create mode 100644 specs/07_vote_extension.md diff --git a/keeper/abci.go b/keeper/abci.go index 22ab009..bd0ee3b 100644 --- a/keeper/abci.go +++ b/keeper/abci.go @@ -105,6 +105,9 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err } currentBlockHeight := ctx.BlockHeight() + + // The following code is executed at block heights that are multiples of the voteInterval, + // i.e., voteInterval+1, 2*voteInterval+1, 3*voteInterval+1, etc. if !k.IsValidBlockToPostTODA(uint64(currentBlockHeight)) { return nil } diff --git a/specs/02_state.md b/specs/02_state.md index 78ec24e..4b750fb 100644 --- a/specs/02_state.md +++ b/specs/02_state.md @@ -49,7 +49,7 @@ It is stored in the state as follows: ## Avail Height -The Avail block height at which the data is made available. +The Avail block height at which the latest blocks data is made available. It is stored in the state as follows: diff --git a/specs/03_msg.md b/specs/03_msg.md index 6125f63..9504a4b 100644 --- a/specs/03_msg.md +++ b/specs/03_msg.md @@ -1,3 +1,14 @@ + + # Messages -## \ No newline at end of file +## UpdateBlobStatus + +The `MsgUpdateBlobStatus` is used to update the status of block submissions from `PENDING` to either `IN_VOTING` if the submission is successful, or `FAILURE` if it fails. The responsibility for executing this transaction lies with the individual who originally submitted the blocks data to `Avail` (the proposer of the block where the blocks data submission was initiated). + +This message will fail under the following conditions: + + If the status is nil, meaning it is neither true nor false. + If the status is true but the Avail height is not a valid number. \ No newline at end of file diff --git a/specs/04_client.md b/specs/04_client.md new file mode 100644 index 0000000..3d028f5 --- /dev/null +++ b/specs/04_client.md @@ -0,0 +1,35 @@ + + +# Client + +A user can query and interact with the `cada` module using the CLI. + + +## Query + +The `query` commands allows users to query `cada` state. + + +```sh +simd query cada --help +``` + +#### Query the Status +The `get-da-status` command enables users to retrieve comprehensive information, including the range of blocks currently being posted to Avail, the current status, the last proven height, the Avail height where the data is made available, and the voting block height by which voting should conclude. + +```sh +$ simd query cada get-da-status +``` + +Output: + +```yml +last_blob_voting_ends_at: "23" +proven_height: "0" +range: + from: "1" + to: "5" +status: IN_VOTING +``` \ No newline at end of file diff --git a/specs/05_prepare_proposal.md b/specs/05_prepare_proposal.md new file mode 100644 index 0000000..4ad655c --- /dev/null +++ b/specs/05_prepare_proposal.md @@ -0,0 +1,59 @@ + + +# ProofOfBlobProposalHandler: PrepareProposal Method + +This documentation provides an overview of the `PrepareProposal` method within the `ProofOfBlobProposalHandler`. This method is critical for preparing a block proposal by aggregating and injecting vote information into the proposal transactions. + +## Method Overview + +The `PrepareProposal` method performs the following key steps: + +### 1. Proposer Address Initialization + +The method starts by setting the `proposerAddress` in the keeper with the address provided in the `RequestPrepareProposal`. This address represents the proposer of the current block. Since the `PrepareProposal` ABCI method is exclusively executed by the block proposer, this address can later be used for posting block data to `Avail`. + +```go +h.keeper.proposerAddress = req.ProposerAddress +``` + + +### 2. Vote Aggregation + +The method then aggregates votes by calling the `aggregateVotes` function, which takes in the current context and the `LocalLastCommit` from the request. This function collects votes from the last commit, which are essential for the consensus process for da verification. + +```go +votes, err := h.aggregateVotes(ctx, req.LocalLastCommit) +if err != nil { + fmt.Println("error while aggregating votes", err) + return nil, err +} +``` + + + +### 3. Injection of Aggregated Votes + +The method creates a new structure, `StakeWeightedVotes`, to hold the aggregated votes and the extended commit information (`ExtendedCommitInfo`). + +```go +injectedVoteExtTx := StakeWeightedVotes{ + Votes: votes, + ExtendedCommitInfo: req.LocalLastCommit, +} +bz, err := json.Marshal(injectedVoteExtTx) +if err != nil { + fmt.Println("failed to encode injected vote extension tx", "err", err) +} +``` + +The serialized vote information (`injectedVoteExtTx`) is appended to the list of proposal transactions, which can be later processed in `PreBlocker` abci method. + +```go +proposalTxs = append(proposalTxs, bz) + +return &abci.ResponsePrepareProposal{ + Txs: proposalTxs, +}, nil +``` \ No newline at end of file diff --git a/specs/06_preblocker.md b/specs/06_preblocker.md new file mode 100644 index 0000000..1870b1a --- /dev/null +++ b/specs/06_preblocker.md @@ -0,0 +1,83 @@ + + +# ProofOfBlobProposalHandler: PreBlocker Method + +This documentation provides a detailed overview of the `PreBlocker` method within the `ProofOfBlobProposalHandler`. This method is crucial for processing vote extensions, updating statuses, and initiating block data submissions to Avail. + +## Method Overview + +The `PreBlocker` method is responsible for two primary tasks: processing votes from vote extensions to update the status and initiating the submission of blocks' data to Avail. Below is a step-by-step explanation of how this method works. + +### 1. Process Votes from Vote Extensions and Update the Status + +When the current block height matches the voting end height and the status is `IN_VOTING`, the method processes the voting results and updates the state accordingly. + +- **Success Condition:** If the collective voting power exceeds 66%, the status is updated to `READY`, and the `provenHeight` is set to the end of the current block range. +- **Failure Condition:** If the voting power is 66% or less, the status is updated to `FAILURE`. + +```go +if len(req.Txs) > 0 && currentHeight == int64(votingEndHeight) && blobStatus == IN_VOTING_STATE { + var injectedVoteExtTx StakeWeightedVotes + if err := json.Unmarshal(req.Txs[0], &injectedVoteExtTx); err != nil { + fmt.Println("preblocker failed to decode injected vote extension tx", "err", err) + } else { + from := k.GetStartHeightFromStore(ctx) + to := k.GetEndHeightFromStore(ctx) + + pendingRangeKey := Key(from, to) + votingPower := injectedVoteExtTx.Votes[pendingRangeKey] + + if votingPower > 66 { // Voting power is greater than 66% + k.setBlobStatusSuccess(ctx) + } else { + k.SetBlobStatusFailure(ctx) + } + } +} +``` + +### 2. Initiate Block Data Availability (DA) Submission + +If the current block height aligns with a voting interval and the status is either `READY` or `FAILURE`, the method updates the block range and sets the status to `PENDING` for the next round of blocks data submission. + +- **Range Calculation:** The pending block range to be submitted is calculated based on the last proven height and the current block height. +- **Status Update:** The status is set to `PENDING` to mark the start of the data submission process. + +```go +// The following code is executed at block heights that are multiples of the voteInterval, +// i.e., voteInterval+1, 2*voteInterval+1, 3*voteInterval+1, etc. +if !k.IsValidBlockToPostTODA(uint64(currentBlockHeight)) { + return nil +} + +provenHeight := k.GetProvenHeightFromStore(ctx) +fromHeight := provenHeight + 1 // Calculate pending range of blocks to post data +endHeight := min(fromHeight+uint64(k.MaxBlocksForBlob), uint64(ctx.BlockHeight())) // Exclusive range i.e., [fromHeight, endHeight) + +sdkCtx := sdk.UnwrapSDKContext(ctx) +ok := k.SetBlobStatusPending(sdkCtx, fromHeight, endHeight-1) +if !ok { + return nil +} +``` + +### 3. Proposer Submits Block Data to Avail DA + +If the node running this method is the proposer of the block, it takes responsibility for submitting the blocks data to Avail DA. + +- **Block Data Submission:** The proposer gathers the blocks within the calculated range and posts them to Avail DA. + +```go +var blocksToSubmit []int64 + +for i := fromHeight; i < endHeight; i++ { + blocksToSubmit = append(blocksToSubmit, int64(i)) +} + +// Only the proposer should execute the following code +if bytes.Equal(req.ProposerAddress, k.proposerAddress) { + k.relayer.PostBlocks(ctx, blocksToSubmit, k.cdc, req.ProposerAddress) +} +``` \ No newline at end of file diff --git a/specs/07_vote_extension.md b/specs/07_vote_extension.md new file mode 100644 index 0000000..285b9fd --- /dev/null +++ b/specs/07_vote_extension.md @@ -0,0 +1,79 @@ + + +# Vote Extensions + +This specification details the functionality and purpose of the `ExtendVoteHandler` and `VerifyVoteExtensionHandler` methods within the VoteExtHandler struct. These methods are part of a voting extension process where validators extend their votes based on the availability of data in the blockchain. + +### ExtendVoteHandler + +The `ExtendVoteHandler` method is responsible for generating a `vote extension`. It checks the availability of specific data in the blockchain by interacting with an Avail light client. The vote extension is then created based on the outcome of this check. + +* The method first begins by retrieving several voting-related parameters, including the start and end heights of the blocks being processed, the availability height, and the status of the current blob (data) + +```go +from := h.Keeper.GetStartHeightFromStore(ctx) + end := h.Keeper.GetEndHeightFromStore(ctx) + + availHeight := h.Keeper.GetAvailHeightFromStore(ctx) + + pendingRangeKey := Key(from, end) + + blobStatus := h.Keeper.GetBlobStatus(ctx) + currentHeight := ctx.BlockHeight() + voteEndHeight := h.Keeper.GetVotingEndHeightFromStore(ctx) +``` + +* The method checks if the current height is just before the end of the voting period and if the blob is in the voting state. If not, it generates a basic vote extension indicating that no data was verified + +```go +if currentHeight+1 != int64(voteEndHeight) || blobStatus != IN_VOTING_STATE { + voteExt := VoteExtension{ + Votes: Votes, + } + + // json marshalling + votesBytes, err := json.Marshal(voteExt) + if err != nil { + return nil, fmt.Errorf("failed to marshal vote extension: %w", err) + } + abciResponseVoteExt.VoteExtension = votesBytes + return abciResponseVoteExt, nil + } +``` + +* If the conditions are met, the method queries the Avail light client to determine if the relevant data is available. The result of this check is recorded in a map +```go + ok, err := h.Keeper.relayer.IsDataAvailable(ctx, from, end, availHeight, "http://localhost:8000") + if ok { + h.logger.Info("submitted data to Avail verified successfully at", + "block_height", availHeight, + ) + } + + + Votes[pendingRangeKey] = ok +``` + +* The outcome (whether the data was available or not) is marshaled into a vote extension and returned as part of the abci.ResponseExtendVote + +```go + voteExt := VoteExtension{ + Votes: Votes, + } + + votesBytes, err := json.Marshal(voteExt) + if err != nil { + return nil, fmt.Errorf("failed to marshal vote extension: %w", err) + } + + return &abci.ResponseExtendVote{ + VoteExtension: votesBytes, + }, nil +``` + +### VerifyVoteExtensionHandler +The `VerifyVoteExtensionHandler` method is responsible for validating the format and content of the vote extensions generated by the `ExtendVoteHandler`. + +This method performs a basic validation check on the received vote extension, ensuring it meets the necessary format requirements. It then returns a response indicating whether the vote extension is accepted. \ No newline at end of file diff --git a/specs/README.md b/specs/README.md index fa7c19f..bf1b7b8 100644 --- a/specs/README.md +++ b/specs/README.md @@ -1,6 +1,17 @@ # `x/cada` +## Table of Conetents +- [Abstract](#abstract) +- [Concepts](01_concepts.md#concepts) +- [State](02_state.md#state) +- [Transactions](03_msg.md#messages) +- [Client](04_client.md#client) +- [PrepareProposal Abci method](05_prepare_proposal.md#proofofblobproposalhandler-prepareproposal-method) +- [PreBlocker Abci method](06_preblocker.md#proofofblobproposalhandler-preblocker-method) +- [Vote Extensions](07_vote_extension.md#vote-extensions) +- [Architecture](#architecture) + ## Abstract From be8cd9869c57d96c0bbde85f72c30063e7a35e83 Mon Sep 17 00:00:00 2001 From: saiteja Date: Wed, 11 Sep 2024 14:57:23 +0530 Subject: [PATCH 49/58] feat: update docs --- specs/README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/specs/README.md b/specs/README.md index bf1b7b8..44db7d1 100644 --- a/specs/README.md +++ b/specs/README.md @@ -25,23 +25,23 @@ CADA is a module designed to connect Cosmos sovereign chains with the Avail netw ## Architecture - - At each block interval, a request is sent from the `PreBlocker` ABCI method to the Keeper, specifying the range of block heights that are ready to be posted to the `Avail` DA network. - - The range of block heights should be from `provenHeight + 1` to `min(provenHeight + MaxBlocksLimitForBlob, CurrentBlockHeight)`. +- At each block interval, a request is sent from the `PreBlocker` ABCI method to the Keeper, specifying the range of block heights that are ready to be posted to the `Avail` DA network. +- The range of block heights should be from `provenHeight + 1` to `min(provenHeight + MaxBlocksLimitForBlob, CurrentBlockHeight)`. - - If the status of the previous blocks is either `READY` or `FAILURE`, the status can be updated to `PENDING`. +- If the status of the previous blocks is either `READY` or `FAILURE`, the status can be updated to `PENDING`. ``` range = [fromBlock, toBlock] // (fromBlock < toBlock < CurrentBlock) status = PENDING ``` - - The `Proposer` of the block will make a request to the `Relayer` to post the blocks data by passing the range of blocks to be posted. +- The `Proposer` of the block will make a request to the `Relayer` to post the blocks data by passing the range of blocks to be posted. - - The `Relayer` fetches the blocks data from the local provider, converts the blocks data to bytes, and posts that data to `Avail`. +- The `Relayer` fetches the blocks data from the local provider, converts the blocks data to bytes, and posts that data to `Avail`. - - Once the success of data availability is confirmed, the `Relayer` broadcasts the `Avail height` at which the blob data is made available using the `MsgUpdateBlobStatus` transaction. +- Once the success of data availability is confirmed, the `Relayer` broadcasts the `Avail height` at which the blob data is made available using the `MsgUpdateBlobStatus` transaction. - - The status, Avail height, and voting deadline will be updated in the state. +- The status, Avail height, and voting deadline will be updated in the state. ``` status = IN_VOTING @@ -49,16 +49,16 @@ CADA is a module designed to connect Cosmos sovereign chains with the Avail netw votingEndBlock = currentBlock + votingInterval ``` - - At block height `VotingEndBlock - 1`, all the validators verify if the specified blocks data is truly made available at the specified Avail height. They cast their vote (YES or NO) using `vote extensions`. +- At block height `VotingEndBlock - 1`, all the validators verify if the specified blocks data is truly made available at the specified Avail height. They cast their vote (YES or NO) using `vote extensions`. - - At block height `VotingEndBlock`, all the votes from `vote_extensions` will be collected and aggregated. If the collective `voting power is > 66%`, the status will be updated +- At block height `VotingEndBlock`, all the votes from `vote_extensions` will be collected and aggregated. If the collective `voting power is > 66%`, the status will be updated ``` status = READY // success and ready for next blocks provenHeight = Range End ``` - - In case of failure at any stage, the whole flow will be repeated. +- In case of failure at any stage, the whole flow will be repeated. --- From 608439d3a139990b77cb3a9628f851c322c0174c Mon Sep 17 00:00:00 2001 From: saiteja Date: Wed, 11 Sep 2024 15:03:59 +0530 Subject: [PATCH 50/58] docs: update specs --- specs/07_vote_extension.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/specs/07_vote_extension.md b/specs/07_vote_extension.md index 285b9fd..60ea478 100644 --- a/specs/07_vote_extension.md +++ b/specs/07_vote_extension.md @@ -4,13 +4,13 @@ order: 7 # Vote Extensions -This specification details the functionality and purpose of the `ExtendVoteHandler` and `VerifyVoteExtensionHandler` methods within the VoteExtHandler struct. These methods are part of a voting extension process where validators extend their votes based on the availability of data in the blockchain. +This specification details the functionality and purpose of the `ExtendVoteHandler` and `VerifyVoteExtensionHandler` methods within the VoteExtHandler struct. These methods are part of a voting extension process where validators extend their votes based on the availability of data in the Avail DA network. ### ExtendVoteHandler -The `ExtendVoteHandler` method is responsible for generating a `vote extension`. It checks the availability of specific data in the blockchain by interacting with an Avail light client. The vote extension is then created based on the outcome of this check. +The `ExtendVoteHandler` method is responsible for generating a `vote extension`. It checks the availability of specific data in the Avail by interacting with an Avail light client. The vote extension is then created based on the outcome of this check. -* The method first begins by retrieving several voting-related parameters, including the start and end heights of the blocks being processed, the availability height, and the status of the current blob (data) +* The method first begins by retrieving several voting-related parameters, including the start and end heights of the blocks being processed, the Avail block height, and the status of the current blob (data) ```go from := h.Keeper.GetStartHeightFromStore(ctx) From a4db1eabc2350185a2f661093aa45135ecc3f97f Mon Sep 17 00:00:00 2001 From: Teja2045 <106052623+Teja2045@users.noreply.github.com> Date: Wed, 11 Sep 2024 16:47:39 +0530 Subject: [PATCH 51/58] Update README.md --- specs/README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/specs/README.md b/specs/README.md index 44db7d1..df03877 100644 --- a/specs/README.md +++ b/specs/README.md @@ -1,4 +1,4 @@ - +![image](https://github.com/user-attachments/assets/8df99a29-913f-4f10-976a-f68cd923a831) # `x/cada` ## Table of Conetents @@ -24,6 +24,9 @@ CADA is a module designed to connect Cosmos sovereign chains with the Avail netw ## Architecture +![blocks-data-submission](https://github.com/user-attachments/assets/4e17b98f-ca8c-4b4c-a79e-8c60f123cb2c) +![vote-extension](https://github.com/user-attachments/assets/c0edb8e7-20fd-468a-9109-4f31718e4467) + - At each block interval, a request is sent from the `PreBlocker` ABCI method to the Keeper, specifying the range of block heights that are ready to be posted to the `Avail` DA network. - The range of block heights should be from `provenHeight + 1` to `min(provenHeight + MaxBlocksLimitForBlob, CurrentBlockHeight)`. From abc5bed8f11153b3ae5e21186af5d42af033a6f4 Mon Sep 17 00:00:00 2001 From: Teja2045 <106052623+Teja2045@users.noreply.github.com> Date: Wed, 11 Sep 2024 16:48:02 +0530 Subject: [PATCH 52/58] Update README.md --- specs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specs/README.md b/specs/README.md index df03877..91ba4bc 100644 --- a/specs/README.md +++ b/specs/README.md @@ -1,4 +1,4 @@ -![image](https://github.com/user-attachments/assets/8df99a29-913f-4f10-976a-f68cd923a831) + # `x/cada` ## Table of Conetents From 393cb1cc23e36562738374a659a851c123fd3daa Mon Sep 17 00:00:00 2001 From: Teja2045 <106052623+Teja2045@users.noreply.github.com> Date: Wed, 11 Sep 2024 16:48:58 +0530 Subject: [PATCH 53/58] Update README.md --- specs/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/specs/README.md b/specs/README.md index 91ba4bc..0563811 100644 --- a/specs/README.md +++ b/specs/README.md @@ -25,7 +25,6 @@ CADA is a module designed to connect Cosmos sovereign chains with the Avail netw ## Architecture ![blocks-data-submission](https://github.com/user-attachments/assets/4e17b98f-ca8c-4b4c-a79e-8c60f123cb2c) -![vote-extension](https://github.com/user-attachments/assets/c0edb8e7-20fd-468a-9109-4f31718e4467) - At each block interval, a request is sent from the `PreBlocker` ABCI method to the Keeper, specifying the range of block heights that are ready to be posted to the `Avail` DA network. @@ -52,6 +51,8 @@ CADA is a module designed to connect Cosmos sovereign chains with the Avail netw votingEndBlock = currentBlock + votingInterval ``` +![vote-extension](https://github.com/user-attachments/assets/c0edb8e7-20fd-468a-9109-4f31718e4467) + - At block height `VotingEndBlock - 1`, all the validators verify if the specified blocks data is truly made available at the specified Avail height. They cast their vote (YES or NO) using `vote extensions`. - At block height `VotingEndBlock`, all the votes from `vote_extensions` will be collected and aggregated. If the collective `voting power is > 66%`, the status will be updated From 111bf0e0ab68bc9bf6802b00d3e60aabc1e262ee Mon Sep 17 00:00:00 2001 From: saiteja Date: Tue, 17 Sep 2024 11:26:47 +0530 Subject: [PATCH 54/58] nit: small changes --- specs/01_concepts.md | 2 +- specs/03_msg.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/specs/01_concepts.md b/specs/01_concepts.md index 59b0352..dd18f5a 100644 --- a/specs/01_concepts.md +++ b/specs/01_concepts.md @@ -23,7 +23,7 @@ For Blob Interval = 5 and Maximum Blocks Limit for Blob = 10 :- ### Relayer -- The `Relayer` acts as the transport layer, responsible for handling requests from the `prepareBlocker` and facilitating transactions between the Cosmos chain and the Avail DA network. +- The `Relayer` acts as the transport layer, responsible for handling requests from the `preBlocker` and facilitating transactions between the Cosmos chain and the Avail DA network. - It performs key functions such as submitting block data to Avail and updating block status on the Cosmos chain. Every validator in the network is required to run the relayer process. - Relayer should initialized with a chain account so that the validator can use this account to sign `MsgUpdateStatusBlob` transaction. diff --git a/specs/03_msg.md b/specs/03_msg.md index 9504a4b..248f45d 100644 --- a/specs/03_msg.md +++ b/specs/03_msg.md @@ -6,7 +6,7 @@ order: 3 ## UpdateBlobStatus -The `MsgUpdateBlobStatus` is used to update the status of block submissions from `PENDING` to either `IN_VOTING` if the submission is successful, or `FAILURE` if it fails. The responsibility for executing this transaction lies with the individual who originally submitted the blocks data to `Avail` (the proposer of the block where the blocks data submission was initiated). +The `MsgUpdateBlobStatus` is used to update the status of blocks submission from `PENDING` to either `IN_VOTING` if the submission is successful, or `FAILURE` if it fails. The responsibility for executing this transaction lies with the individual who originally submitted the blocks data to `Avail` (the proposer of the block where the blocks data submission was initiated). This message will fail under the following conditions: From 3faf8f50f32c82289938bfef17ac45390a1280b0 Mon Sep 17 00:00:00 2001 From: saiteja Date: Tue, 17 Sep 2024 11:59:27 +0530 Subject: [PATCH 55/58] chore: conflicts --- client/client.go | 29 ------- keeper/client.go | 180 ---------------------------------------- relayer/process_blob.go | 28 ------- 3 files changed, 237 deletions(-) delete mode 100644 client/client.go delete mode 100644 keeper/client.go delete mode 100644 relayer/process_blob.go diff --git a/client/client.go b/client/client.go deleted file mode 100644 index 22692c3..0000000 --- a/client/client.go +++ /dev/null @@ -1,29 +0,0 @@ -package client - -import ( - "bytes" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" -) - -const ( - KeyringBackendTest = "test" -) - -// ChainClient is client to interact with SPN. -type ChainClient struct { - factory tx.Factory - clientCtx client.Context - out *bytes.Buffer - Address string `json:"address"` - AddressPrefix string `json:"account_address_prefix"` - RPC string `json:"rpc"` - Key string `json:"key"` - Mnemonic string `json:"mnemonic"` - KeyringServiceName string `json:"keyring_service_name"` - HDPath string `json:"hd_path"` - Enabled bool `json:"enabled"` - ChainName string `json:"chain_name"` - Denom string `json:"denom"` -} diff --git a/keeper/client.go b/keeper/client.go deleted file mode 100644 index 3f14e36..0000000 --- a/keeper/client.go +++ /dev/null @@ -1,180 +0,0 @@ -package keeper - -// import ( -// "fmt" - -// cometrpc "github.com/cometbft/cometbft/rpc/client/http" -// "github.com/cosmos/cosmos-sdk/client" -// "github.com/cosmos/cosmos-sdk/client/flags" -// "github.com/cosmos/cosmos-sdk/client/tx" -// "github.com/cosmos/cosmos-sdk/codec" -// codectypes "github.com/cosmos/cosmos-sdk/codec/types" -// "github.com/cosmos/cosmos-sdk/crypto/hd" -// "github.com/cosmos/cosmos-sdk/crypto/keyring" -// "github.com/cosmos/cosmos-sdk/std" -// sdk "github.com/cosmos/cosmos-sdk/types" -// "github.com/cosmos/cosmos-sdk/types/tx/signing" -// authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" -// authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -// "github.com/cosmos/go-bip39" - -// // "github.com/tendermint/starport/starport/pkg/xfilepath" - -// "github.com/cosmos/cosmos-sdk/types/module" -// ) - -// const ( -// defaultGasAdjustment = 1.0 -// defaultGasLimit = 300000 -// ) - -// // var availdHomePath = xfilepath.JoinFromHome(xfilepath.Path("availsdk")) - -// func NewClientCtx(kr keyring.Keyring, c *cometrpc.HTTP, chainID string, -// cdc codec.BinaryCodec, homepath string, fromAddress sdk.AccAddress) client.Context { -// encodingConfig := MakeEncodingConfig() - -// broadcastMode := flags.BroadcastSync - -// // homepath := "/home/vitwit/.availsdk" - -// return client.Context{}. -// WithCodec(cdc.(codec.Codec)). -// WithChainID(chainID). -// WithFromAddress(fromAddress). -// WithFromName("testkey"). -// WithKeyringDir(homepath). -// WithBroadcastMode(broadcastMode). -// WithTxConfig(authTx.NewTxConfig(cdc.(codec.Codec), authTx.DefaultSignModes)). -// WithKeyring(kr). -// WithAccountRetriever(authtypes.AccountRetriever{}). -// WithClient(c).WithInterfaceRegistry(encodingConfig.InterfaceRegistry). -// WithSkipConfirmation(true) -// } - -// // NewFactory creates a new Factory. -// func NewFactory(clientCtx client.Context) tx.Factory { -// return tx.Factory{}. -// WithChainID(clientCtx.ChainID). -// WithKeybase(clientCtx.Keyring). -// WithGas(defaultGasLimit). -// WithGasAdjustment(defaultGasAdjustment). -// WithSignMode(signing.SignMode_SIGN_MODE_DIRECT). -// WithAccountRetriever(clientCtx.AccountRetriever). -// WithTxConfig(clientCtx.TxConfig) -// } - -// // MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. -// func MakeEncodingConfig(modules ...module.AppModuleBasic) EncodingConfig { -// aminoCodec := codec.NewLegacyAmino() -// interfaceRegistry := codectypes.NewInterfaceRegistry() -// codec := codec.NewProtoCodec(interfaceRegistry) -// txCfg := authTx.NewTxConfig(codec, authTx.DefaultSignModes) - -// encCfg := EncodingConfig{ -// InterfaceRegistry: interfaceRegistry, -// Codec: codec, -// TxConfig: txCfg, -// Amino: aminoCodec, -// } - -// mb := module.NewBasicManager(modules...) - -// std.RegisterLegacyAminoCodec(encCfg.Amino) -// std.RegisterInterfaces(encCfg.InterfaceRegistry) -// mb.RegisterLegacyAminoCodec(encCfg.Amino) -// mb.RegisterInterfaces(encCfg.InterfaceRegistry) - -// return encCfg -// } - -// // func MakeTestEncodingConfig(modules ...module.AppModuleBasic) TestEncodingConfig { -// // aminoCodec := codec.NewLegacyAmino() -// // interfaceRegistry := testutil.CodecOptions{}.NewInterfaceRegistry() -// // codec := codec.NewProtoCodec(interfaceRegistry) - -// // encCfg := TestEncodingConfig{ -// // InterfaceRegistry: interfaceRegistry, -// // Codec: codec, -// // TxConfig: tx.NewTxConfig(codec, tx.DefaultSignModes), -// // Amino: aminoCodec, -// // } - -// // mb := module.NewBasicManager(modules...) - -// // std.RegisterLegacyAminoCodec(encCfg.Amino) -// // std.RegisterInterfaces(encCfg.InterfaceRegistry) -// // mb.RegisterLegacyAminoCodec(encCfg.Amino) -// // mb.RegisterInterfaces(encCfg.InterfaceRegistry) - -// // return encCfg -// // } - -// // EncodingConfig specifies the concrete encoding types to use for a given app. -// // This is provided for compatibility between protobuf and amino implementations. -// type EncodingConfig struct { -// InterfaceRegistry codectypes.InterfaceRegistry -// Codec codec.Codec -// TxConfig client.TxConfig -// Amino *codec.LegacyAmino -// } - -// // ImportMnemonic is to import existing account mnemonic in keyring -// func ImportMnemonic(keyName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { -// info, err := AccountCreate(keyName, mnemonic, hdPath, c) // return account also -// // fmt.Println("here the accc details.......", keyName, mnemonic, hdPath) -// if err != nil { -// return nil, err -// } - -// return info, nil -// } - -// // AccountCreate creates an account by name and mnemonic (optional) in the keyring. -// func AccountCreate(accountName, mnemonic, hdPath string, c client.Context) (*keyring.Record, error) { -// if mnemonic == "" { -// entropySeed, err := bip39.NewEntropy(256) -// if err != nil { -// return nil, err -// } -// mnemonic, err = bip39.NewMnemonic(entropySeed) -// fmt.Println("mnemoniccccc here.....", mnemonic) -// if err != nil { -// return nil, err -// } -// } - -// algos, _ := c.Keyring.SupportedAlgorithms() -// algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algos) -// if err != nil { -// return nil, err -// } - -// path := hd.CreateHDPath(118, 0, 0).String() -// // fmt.Println("pathhh......", path) - -// // record, str, err := c.Keyring.NewMnemonic("test_key1", keyring.English, path, keyring.DefaultBIP39Passphrase, hd.Secp256k1) -// // fmt.Println("recorddddd.......", err, str, record) - -// // k, _, err = kb.NewMnemonic("test", English, types.FullFundraiserPath, DefaultBIP39Passphrase, hd.Secp256k1) -// info, err := c.Keyring.NewAccount(accountName, mnemonic, keyring.DefaultBIP39Passphrase, path, algo) -// fmt.Println("after creationnnn.........", info, err) -// if err != nil { -// return nil, err -// } -// // pk, err := info.GetPubKey() -// // if err != nil { -// // return nil, err -// // } - -// // addr := sdk.AccAddress(pk.Address()) -// // fmt.Println("address hereee...", addr) - -// // aa, err := info.GetAddress() -// // fmt.Println("here aa and err.......", aa, err) - -// // account := c.ToAccount(info) -// // account.Mnemonic = mnemonic -// return info, nil -// // return nil -// } diff --git a/relayer/process_blob.go b/relayer/process_blob.go deleted file mode 100644 index 38435d6..0000000 --- a/relayer/process_blob.go +++ /dev/null @@ -1,28 +0,0 @@ -package relayer - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/spf13/cobra" - "github.com/vitwit/avail-da-module/types" -) - -func (r *Relayer) StartBlobLifeCycle(msg types.MsgSubmitBlobRequest, cmd *cobra.Command) { - - fmt.Println("inside like cycle.................", msg, cmd == nil) - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - fmt.Println("error in start blob life cycle", err) - return - } - - msg.ValidatorAddress = clientCtx.GetFromAddress().String() - err = tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - if err != nil { - fmt.Println("error in start blob life cycle", err) - return - } - fmt.Println("broadcast success..........") -} From a01869608b7bb9d92bacec0dd37246c0d843e153 Mon Sep 17 00:00:00 2001 From: Teja2045 <106052623+Teja2045@users.noreply.github.com> Date: Tue, 17 Sep 2024 17:20:51 +0530 Subject: [PATCH 56/58] Update 07_vote_extension.md --- specs/07_vote_extension.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/specs/07_vote_extension.md b/specs/07_vote_extension.md index 60ea478..4043aa7 100644 --- a/specs/07_vote_extension.md +++ b/specs/07_vote_extension.md @@ -4,6 +4,8 @@ order: 7 # Vote Extensions +Vote extensions are used to propagate arbitrary data across the network without needing to implement transactions that modify the state. Validators utilize vote extensions to verify data availability of a specific range of blocks and update the state of the Cada module accordingly. + This specification details the functionality and purpose of the `ExtendVoteHandler` and `VerifyVoteExtensionHandler` methods within the VoteExtHandler struct. These methods are part of a voting extension process where validators extend their votes based on the availability of data in the Avail DA network. ### ExtendVoteHandler @@ -76,4 +78,4 @@ if currentHeight+1 != int64(voteEndHeight) || blobStatus != IN_VOTING_STATE { ### VerifyVoteExtensionHandler The `VerifyVoteExtensionHandler` method is responsible for validating the format and content of the vote extensions generated by the `ExtendVoteHandler`. -This method performs a basic validation check on the received vote extension, ensuring it meets the necessary format requirements. It then returns a response indicating whether the vote extension is accepted. \ No newline at end of file +This method performs a basic validation check on the received vote extension, ensuring it meets the necessary format requirements. It then returns a response indicating whether the vote extension is accepted. From 1205901754dccdc939bf1c8d97dc3f8ac517b836 Mon Sep 17 00:00:00 2001 From: saiteja Date: Thu, 19 Sep 2024 10:52:59 +0530 Subject: [PATCH 57/58] docs: add requirements --- README.md | 53 ++++------------------------------------------------- 1 file changed, 4 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index f90fc06..800d950 100644 --- a/README.md +++ b/README.md @@ -4,57 +4,12 @@ CADA is a module designed to connect Cosmos sovereign chains with the Avail netw For example: Let blobInterval = 10, + - At height `11`, blocks from `1` to `10` are posted. - At height `21`, blocks from `11` to `20` are posted. -#### Relayer -The `Relayer` acts as the transport layer, responsible for handling requests from the `prepareBlocker` and facilitating transactions between the Cosmos chain and the Avail DA network. It performs key functions such as submitting block data to Avail and updating block status on the Cosmos chain. Every validator in the network is required to run the relayer process. - -#### Proven Height -The `Proven Height` signifies the most recent block height of the Cosmos chain where data has been successfully transmitted to Avail and validated by the network. - -## Architecture - -![Screenshot from 2024-08-27 11-35-01](https://github.com/user-attachments/assets/1a8657f6-4c1b-418a-8295-05c039baa6d0) - - -1. **Block Interval Trigger**: - - At each block interval, a request is sent from `PrepareProposal` abci method to the relayer, specifying the range of block heights to be posted to the Avail DA network. This request should be made by the block proposer only. - -2. **MsgSubmitBlobRequest Transaction**: - - The relayer submits a `MsgSubmitBlobRequest` transaction on the Cosmos chain, signaling that the block data for the specified range is pending: - ``` - status[range] = pending - ``` - - The relayer monitors the transaction to confirm its successful inclusion and processing on the chain. - -3. **Data Submission to Avail DA**: - - Once the `MsgSubmitBlobRequest` transaction is confirmed, the relayer fetches the block data for the specified range and submits it to the Avail DA layer. - -4. **MsgUpdateBlobStatusRequest Transaction**: - - After confirming that the data is available on Avail, the relayer submits a `MsgUpdateBlobStatusRequest` transaction on the Cosmos chain, updating the block status to pre-verification: - ``` - status[range] = IN_VOTING - ``` - -5. **Validator Confirmation**: - - Within a preconfigured block limit, all validators are required to verify the data's availability on the Avail network using their Avail light clients and cast their votes. - - we could use voteExtension to cast the votes - -6. **Consensus and Proven Height Update**: - - If the number of votes exceeds the consensus threshold, the status of the block range is updated to success, and the `Proven Height` is advanced: - ``` - status[range] = success - - // Update the proven height - if range.from == provenHeight + 1 { - provenHeight = range.to - } - ``` +Refer to the module specification available here for more detailed information. -7. **Failure Handling**: - - In case of any failures or expiration of the verification window, the data will be reposted following the same procedure. +Note: Use the latest maintained [Go]{https://go.dev/dl/} version to work with this module. ---- -For detailed instructions on how to integrate the module with a spawn generated application, please refer to the [integration guide](./docs/spawn.md). +Ensure that the Avail light client URL is correctly configured for the module to function as expected. For instructions on running Avail locally, refer to this documentation. From ff4dd32bca370b437b353f72181ef084958b69cc Mon Sep 17 00:00:00 2001 From: Teja2045 <106052623+Teja2045@users.noreply.github.com> Date: Thu, 19 Sep 2024 10:57:34 +0530 Subject: [PATCH 58/58] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 800d950..a123e17 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ Let blobInterval = 10, - At height `11`, blocks from `1` to `10` are posted. - At height `21`, blocks from `11` to `20` are posted. -Refer to the module specification available here for more detailed information. +Refer to the module specification available [here](./specs/README.md) for more detailed information. -Note: Use the latest maintained [Go]{https://go.dev/dl/} version to work with this module. +Note: Use the latest maintained [Go](https://go.dev/dl/) version to work with this module. -Ensure that the Avail light client URL is correctly configured for the module to function as expected. For instructions on running Avail locally, refer to this documentation. +Ensure that the Avail light client URL is correctly configured for the module to function as expected. For instructions on running Avail locally, refer to [this documentation](https://github.com/rollkit/avail-da?tab=readme-ov-file#avail-da).