Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions types/query/pagination.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ func Paginate(
onResult func(key, value []byte) error,
) (*PageResponse, error) {
pageRequest = initPageRequestDefaults(pageRequest)
pageRequest = ClampPageRequestLimit(pageRequest)

if pageRequest.Offset > 0 && pageRequest.Key != nil {
return nil, fmt.Errorf("invalid request, either offset or key is expected, got both")
Expand Down Expand Up @@ -158,3 +159,16 @@ func initPageRequestDefaults(pageRequest *PageRequest) *PageRequest {

return &pageRequestCopy
}

// ClampPageRequestLimit returns a safe Limit such that Offset+Limit never overflows uint64.
func ClampPageRequestLimit(pageRequest *PageRequest) *PageRequest {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably prefer to keep this as a private function - no need to export

if pageRequest == nil {
return &PageRequest{}
}

pageRequestCopy := *pageRequest
if pageRequestCopy.Limit > PaginationMaxLimit-pageRequestCopy.Offset {
pageRequestCopy.Limit = PaginationMaxLimit - pageRequestCopy.Offset
}
return &pageRequestCopy
}
14 changes: 14 additions & 0 deletions types/query/pagination_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,3 +375,17 @@ func (s *paginationTestSuite) TestPaginate() {
// Output:
// balances:<denom:"foo0denom" amount:"100" > pagination:<next_key:"foo1denom" total:2 >
}

func (s *paginationTestSuite) TestClampOverflow() {
s.T().Log("verify that Limit is clamped when Offset+Limit would overflow")

pageReq := &query.PageRequest{
Offset: uint64(5),
Limit: ^uint64(0),
}

clamped := query.ClampPageRequestLimit(pageReq)

want := query.PaginationMaxLimit - clamped.Offset
s.Require().Equal(want, clamped.Limit)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably want more test cases

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what about the happy path?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review!
I'll add more comprehensive test cases including happy path scenarios and will update the PR soon

}