Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
NagaTulasi committed Sep 17, 2024
2 parents 97f5a9f + da99450 commit 0082be1
Show file tree
Hide file tree
Showing 32 changed files with 829 additions and 3,748 deletions.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
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.

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` represents the latest block height of the Cosmos chain for which data has been successfully posted to Avail and verified by the network.
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

Expand All @@ -21,19 +22,19 @@ The `Proven Height` represents the latest block height of the Cosmos chain for w
- 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:
- 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 tracks the transaction to ensure its successful completion.
- 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] = pre_verification
status[range] = IN_VOTING
```
5. **Validator Confirmation**:
Expand Down
29 changes: 29 additions & 0 deletions chainclient/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package chainclient

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"`
}
37 changes: 0 additions & 37 deletions client/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,43 +62,6 @@ func (s *IntegrationTestSuite) TearDownSuite() {
s.network.Cleanup()
}

func (s *IntegrationTestSuite) TestNewSubmitBlobCmd() {
val := s.network.Validators[0]

testCases := []struct {
name string
args []string
expectErr bool
}{
{
"submit blocks",
[]string{
"1",
"10",
fmt.Sprintf("--%s=%s", flags.FlagFrom, s.addresses[0]),
fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation),
fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync),
},
false,
},
}

for _, tc := range testCases {
s.Run(tc.name, func() {
cmd := cli.NewSubmitBlobCmd()
res, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, tc.args)
if tc.expectErr {
if err != nil {
s.Require().Error(err)
}
}

s.Require().NoError(nil)
s.Require().NotNil(res)
})
}
}

func (s *IntegrationTestSuite) TestNewUpdateBlobStatusCmd() {
val := s.network.Validators[0]

Expand Down
12 changes: 9 additions & 3 deletions client/cli/query.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cli

import (
"log"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/spf13/cobra"
Expand All @@ -26,16 +28,20 @@ func GetLatestBlobStatusInfo() *cobra.Command {
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),
Example: "simd query cada get-da-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)
req := &types.QuerySubmittedBlobStatusRequest{}
res, err := queryClient.SubmittedBlobStatus(cmd.Context(), req)
if err != nil {
log.Fatal(err)
}

return clientCtx.PrintProto(res)
},
Expand Down
68 changes: 2 additions & 66 deletions client/cli/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cli

import (
"errors"
"fmt"
"strconv"
"strings"

Expand All @@ -27,81 +26,18 @@ func NewTxCmd(keeper *keeper.Keeper) *cobra.Command {
RunE: client.ValidateCmd,
}

// keeper.ClientCmd = txCmd

txCmd.AddCommand(NewSubmitBlobCmd())
txCmd.AddCommand(NewUpdateBlobStatusCmd(), InitKepperClientCmd(keeper))
txCmd.AddCommand(NewUpdateBlobStatusCmd())

return txCmd
}

// init keeper client cmd
func InitKepperClientCmd(keeper *keeper.Keeper) *cobra.Command {
cmd := &cobra.Command{
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
},
}

flags.AddTxFlagsToCmd(cmd)

return cmd
}

// 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(),
}

// cmd.Marsha
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",
Example: "simd update-blob 11 15 success 120",
Args: cobra.ExactArgs(4),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ require (
github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect
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
github.com/cosmos/cosmos-db v1.0.2 // 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
Expand Down
18 changes: 5 additions & 13 deletions keeper/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,6 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
)

type StakeWeightedVotes struct {
Votes map[string]int64
ExtendedCommitInfo abci.ExtendedCommitInfo
}

type ProofOfBlobProposalHandler struct {
keeper *Keeper

Expand Down Expand Up @@ -96,11 +91,13 @@ func (k *Keeper) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) err
pendingRangeKey := Key(from, to)
votingPower := injectedVoteExtTx.Votes[pendingRangeKey]

state := FAILURE_STATE

if votingPower > 0 { // TODO: calculate voting power properly
k.setBlobStatusSuccess(ctx)
} else {
k.SetBlobStatusFailure(ctx)
state = READY_STATE
}

k.SetBlobStatus(ctx, state)
}
}

Expand Down Expand Up @@ -152,8 +149,6 @@ func (h *ProofOfBlobProposalHandler) aggregateVotes(ctx sdk.Context, ci abci.Ext
pendingRangeKey := Key(from, to)
votes := make(map[string]int64, 1)

var totalStake int64

for _, v := range ci.Votes {
// Process only votes with BlockIDFlagCommit, indicating the validator committed to the block.
// Skip votes with other flags (e.g., BlockIDFlagUnknown, BlockIDFlagNil).
Expand All @@ -171,9 +166,6 @@ func (h *ProofOfBlobProposalHandler) aggregateVotes(ctx sdk.Context, ci abci.Ext
continue
}

// TODO: remove if this is not used anywhere
totalStake += v.Validator.Power

for voteRange, isVoted := range voteExt.Votes {
if voteRange != pendingRangeKey || !isVoted {
continue
Expand Down
8 changes: 8 additions & 0 deletions keeper/abciTypes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package keeper

import abci "github.com/cometbft/cometbft/abci/types"

type StakeWeightedVotes struct {
Votes map[string]int64
ExtendedCommitInfo abci.ExtendedCommitInfo
}
26 changes: 0 additions & 26 deletions keeper/collections.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,29 +193,3 @@ func (k Keeper) GetExpiredBlocks(ctx context.Context, currentBlockTime time.Time
}
return expiredBlocks
}

func (k *Keeper) GetPendingBlocksWithExpiration(ctx context.Context) ([]*types.BlockWithExpiration, error) {
iterator, err := k.PendingBlocksToTimeouts.Iterate(ctx, nil)
if err != nil {
return nil, err
}
defer iterator.Close()

var pendingBlocks []*types.BlockWithExpiration
for ; iterator.Valid(); iterator.Next() {
pendingBlock, err := iterator.Key()
if err != nil {
return nil, err
}
expiration, err := iterator.Value()
if err != nil {
return nil, err
}
pendingBlocks = append(pendingBlocks, &types.BlockWithExpiration{
Height: pendingBlock,
Expiration: time.Unix(0, expiration),
})
}

return pendingBlocks, nil
}
3 changes: 0 additions & 3 deletions keeper/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,13 @@ func (k *Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState {
panic(err)
}

pendingBlocks, err := k.GetPendingBlocksWithExpiration(ctx)
if err != nil {
panic(err)
}

return &types.GenesisState{
Validators: vals.Validators,
ProvenHeight: provenHeight,

PendingBlocks: pendingBlocks,
}
}

Expand Down
Loading

0 comments on commit 0082be1

Please sign in to comment.