Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[OTE-553] Timestamp nonce #1970

Merged
merged 21 commits into from
Jul 26, 2024
Merged

[OTE-553] Timestamp nonce #1970

merged 21 commits into from
Jul 26, 2024

Conversation

jerryfan01234
Copy link
Contributor

@jerryfan01234 jerryfan01234 commented Jul 25, 2024

Changelist

Refactor

Test Plan

[Describe how this PR was tested (if applicable)]

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced transaction handling in the accountplus module, improving robustness and clarity.
    • Introduced functions for validating and processing timestamp nonce transactions, ensuring accurate transaction sequencing.
  • Bug Fixes

    • Improved error handling and telemetry for timestamp nonce validation, enhancing performance monitoring.
  • Tests

    • Added comments and TODOs to improve the organization of test cases related to timestamp nonce functionality.
  • Chores

    • Removed outdated tests and reorganized test coverage strategy for the accountplus functionality.

Copy link
Contributor

coderabbitai bot commented Jul 25, 2024

Walkthrough

The recent updates enhance transaction handling and validation within the accountplus module of the protocol. Key improvements include refined nonce verification, streamlined error management, and new methods for processing timestamp nonces. These changes aim to bolster robustness, clarity, and performance monitoring across the transaction lifecycle, ultimately strengthening the integrity of blockchain interactions.

Changes

Files Change Summary
protocol/app/ante.go Enhanced transaction handling logic with new imports, modified NewAnteHandler to standardize decorators, and improved decision-making for nonce transactions.
protocol/app/ante/sigverify.go Updated timestamp nonce handling in SigVerificationDecorator, introduced telemetry for nonce validation, and streamlined error handling for account state.
protocol/x/accountplus/ante/timestampnonce.go Introduced IsTimestampNonceTx function to validate transactions with timestamp nonces and added ProcessTimestampNonce for handling nonce processing.
protocol/x/accountplus/keeper/keeper_test.go Removed TestInitializeAccount, suggesting a shift in testing strategy with a note for future tests on Get and Set functions.
protocol/x/accountplus/keeper/timestampnonce_test.go Added comments about testing for ProcessTimestampNonce, referencing existing tests and indicating plans for improved organization in test cases.

Sequence Diagram(s)

sequenceDiagram
    participant A as User
    participant T as Transaction Handler
    participant V as SigVerificationDecorator
    participant K as Keeper

    A->>T: Submit transaction
    T->>T: Check nonce validity
    T->>V: Validate signature
    V->>K: Process timestamp nonce
    K-->>T: Return nonce status
    T-->>A: Confirm transaction status
Loading

🐰 In the fields so bright and green,
A new dawn for transactions is seen.
With timestamps and nonces in play,
Our ledger's integrity holds sway.
Hopping through code, so clever and spry,
Watch our blockchain leap and fly! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@jerryfan01234 jerryfan01234 changed the title Timestamp nonce [OTE-553] Timestamp nonce Jul 25, 2024
Copy link

linear bot commented Jul 25, 2024

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

Outside diff range, codebase verification and nitpick comments (3)
protocol/x/accountplus/keeper/timestampnonce.go (3)

Line range hint 44-57:
Optimize the loop for better performance.

The loop can be optimized by preallocating the slice for newTsNonces to avoid multiple allocations during append operations.

func EjectStaleTimestampNonces(accountState *types.AccountState, referenceTs uint64) {
	tsNonceDetails := &accountState.TimestampNonceDetails
	newTsNonces := make([]uint64, 0, len(tsNonceDetails.TimestampNonces))
	for _, tsNonce := range tsNonceDetails.TimestampNonces {
		if tsNonce >= referenceTs-MaxTimeInPastMs {
			newTsNonces = append(newTsNonces, tsNonce)
		} else {
			if tsNonce > tsNonceDetails.MaxEjectedNonce {
				tsNonceDetails.MaxEjectedNonce = tsNonce
			}
		}
	}
	tsNonceDetails.TimestampNonces = newTsNonces
}

Line range hint 59-78:
Consider logging nonce rejection for better debugging.

When a nonce is rejected, consider adding a log entry to help with debugging and monitoring.

if tsNonce <= tsNonceDetails.MaxEjectedNonce {
	fmt.Printf("Nonce %d rejected: less than or equal to MaxEjectedNonce %d", tsNonce, tsNonceDetails.MaxEjectedNonce)
	return false
}

if len(tsNonceDetails.TimestampNonces) < MaxTimestampNonceArrSize {
	tsNonceDetails.TimestampNonces = append(tsNonceDetails.TimestampNonces, tsNonce)
	return true
}

isSufficientlyLargeTsNonce, minIdx := isLargerThanSmallestValue(tsNonce, tsNonceDetails.TimestampNonces)
if isSufficientlyLargeTsNonce {
	tsNonceDetails.MaxEjectedNonce = tsNonceDetails.TimestampNonces[minIdx]
	tsNonceDetails.TimestampNonces[minIdx] = tsNonce
	return true
}

fmt.Printf("Nonce %d rejected: not larger than smallest value", tsNonce)
return false

Line range hint 80-99:
Consider handling edge cases for empty slices.

The function currently handles empty slices by returning false, -1, but consider adding a log entry for better debugging.

// Check if input value is larger than smallest value in arr and return index of the min value. If minimum value has
// duplicates, will return smallest index. index = -1 empty slice.
func isLargerThanSmallestValue(value uint64, values []uint64) (bool, int) {
	if len(values) == 0 {
		fmt.Printf("Empty slice provided for comparison with value %d", value)
		return false, -1
	}

	minIndex := 0
	for i, ts := range values {
		if ts < values[minIndex] {
			minIndex = i
		}
	}

	if value > values[minIndex] {
		return true, minIndex
	} else {
		return false, minIndex
	}
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2887f7b and 0e28134.

Files selected for processing (9)
  • protocol/app/ante.go (5 hunks)
  • protocol/app/ante/sigverify.go (4 hunks)
  • protocol/lib/metrics/constants.go (2 hunks)
  • protocol/x/accountplus/ante/timestampnonce.go (1 hunks)
  • protocol/x/accountplus/ante/timestampnonce_test.go (1 hunks)
  • protocol/x/accountplus/keeper/keeper.go (2 hunks)
  • protocol/x/accountplus/keeper/keeper_test.go (1 hunks)
  • protocol/x/accountplus/keeper/timestampnonce.go (2 hunks)
  • protocol/x/accountplus/keeper/timestampnonce_test.go (1 hunks)
Files skipped from review due to trivial changes (2)
  • protocol/x/accountplus/keeper/keeper_test.go
  • protocol/x/accountplus/keeper/timestampnonce_test.go
Additional comments not posted (13)
protocol/x/accountplus/ante/timestampnonce.go (1)

1-9: LGTM! Imports are well-organized.

The imports are correctly organized and relevant to the functionality provided in this file.

protocol/x/accountplus/keeper/keeper.go (1)

67-74: Potential risk of overwriting existing account states.

The new method GetAccountPlusStateWithTimestampNonceDetails assumes that the caller ensures the account state does not already exist. This could lead to unintentional overwrites of account states.

Ensure that the method is called only when the account state does not already exist. Consider adding a check or documentation to highlight this assumption.

protocol/x/accountplus/ante/timestampnonce_test.go (3)

1-17: LGTM! Imports and package declaration are well-organized.

The imports and package declaration are correctly organized and relevant to the test functionality provided in this file.


19-73: Comprehensive test coverage.

The tests cover various scenarios for the function IsTimestampNonceTx, ensuring robust validation.


75-85: LGTM! Helper function is well-implemented.

The helper function getSignature is correctly implemented and aids in creating test signatures.

protocol/x/accountplus/keeper/timestampnonce.go (1)

23-42: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to ProcessTimestampNonce match the new logic.

Verification successful

Function usage and testing confirmed

The function ProcessTimestampNonce is correctly used in the codebase and is adequately covered by test cases in sigverify_test.go.

  • Verified usage in protocol/app/ante/sigverify.go.
  • Verified test coverage in protocol/app/ante/sigverify_test.go.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `ProcessTimestampNonce` match the new logic.

# Test: Search for the function usage. Expect: Only occurrences of the new logic.
rg --type go -A 5 $'ProcessTimestampNonce'

Length of output: 1802


Script:

#!/bin/bash
# Extract relevant lines around the function call in sigverify.go
rg --type go -A 10 -B 10 'ProcessTimestampNonce' protocol/app/ante/sigverify.go

# Extract relevant lines around the test cases in sigverify_test.go
rg --type go -A 10 -B 10 'ProcessTimestampNonce' protocol/app/ante/sigverify_test.go

Length of output: 983


Script:

#!/bin/bash
# Search for references to sigverify in the test files to ensure adequate testing of ProcessTimestampNonce
rg --type go -A 10 -B 10 'sigverify' protocol/app/ante/sigverify_test.go

Length of output: 823


Script:

#!/bin/bash
# Search for test functions in sigverify_test.go to confirm execution of test cases involving ProcessTimestampNonce
rg --type go -A 5 -B 5 'func Test' protocol/app/ante/sigverify_test.go

Length of output: 643

protocol/app/ante/sigverify.go (2)

Line range hint 20-27:
LGTM!

The initialization logic is clear and follows best practices.


103-120: Ensure telemetry metrics are consistent.

The telemetry metrics for valid and invalid timestamp nonces should be consistent and provide meaningful insights.

protocol/app/ante.go (3)

156-156: Ensure the standard sequence increment logic is sufficient.

The switch to the standard ante.IncrementSequenceDecorator should be verified to ensure it meets all requirements previously handled by the custom implementation.


117-117: Ensure the standard sequence increment logic is sufficient.

The switch to the standard ante.NewIncrementSequenceDecorator should be verified to ensure it meets all requirements previously handled by the custom implementation.


117-117: Ensure the standard sequence increment logic is sufficient.

The switch to the standard ante.NewIncrementSequenceDecorator should be verified to ensure it meets all requirements previously handled by the custom implementation.

protocol/lib/metrics/constants.go (2)

14-14: LGTM!

The addition of the ExecMode constant is correctly placed and consistent with the existing constants.


412-412: LGTM!

The addition of the TimestampNonce constant is correctly placed and consistent with the existing constants.

Comment on lines 11 to 32
// IsTimestampNonceTx returns `true` if the supplied `tx` consist of a single signature that uses a timestamp nonce
// value for sequence
func IsTimestampNonceTx(ctx sdk.Context, tx sdk.Tx) (bool, error) {
sigTx, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
return false, errorsmod.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type")
}
signatures, err := sigTx.GetSignaturesV2()
if err != nil {
return false, err
}

if len(signatures) != 1 {
return false, errorsmod.Wrap(sdkerrors.ErrTxDecode, "more than one signature")
}

if accountpluskeeper.IsTimestampNonce(signatures[0].Sequence) {
return true, nil
} else {
return false, nil
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure comprehensive error handling.

The function IsTimestampNonceTx correctly checks the transaction type and retrieves signatures. However, consider logging the errors for better traceability.

-  return false, errorsmod.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type")
+  err := errorsmod.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type")
+  ctx.Logger().Error(err.Error())
+  return false, err

-  return false, errorsmod.Wrap(sdkerrors.ErrTxDecode, "more than one signature")
+  err := errorsmod.Wrap(sdkerrors.ErrTxDecode, "more than one signature")
+  ctx.Logger().Error(err.Error())
+  return false, err
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// IsTimestampNonceTx returns `true` if the supplied `tx` consist of a single signature that uses a timestamp nonce
// value for sequence
func IsTimestampNonceTx(ctx sdk.Context, tx sdk.Tx) (bool, error) {
sigTx, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
return false, errorsmod.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type")
}
signatures, err := sigTx.GetSignaturesV2()
if err != nil {
return false, err
}
if len(signatures) != 1 {
return false, errorsmod.Wrap(sdkerrors.ErrTxDecode, "more than one signature")
}
if accountpluskeeper.IsTimestampNonce(signatures[0].Sequence) {
return true, nil
} else {
return false, nil
}
}
// IsTimestampNonceTx returns `true` if the supplied `tx` consist of a single signature that uses a timestamp nonce
// value for sequence
func IsTimestampNonceTx(ctx sdk.Context, tx sdk.Tx) (bool, error) {
sigTx, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
err := errorsmod.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type")
ctx.Logger().Error(err.Error())
return false, err
}
signatures, err := sigTx.GetSignaturesV2()
if err != nil {
return false, err
}
if len(signatures) != 1 {
err := errorsmod.Wrap(sdkerrors.ErrTxDecode, "more than one signature")
ctx.Logger().Error(err.Error())
return false, err
}
if accountpluskeeper.IsTimestampNonce(signatures[0].Sequence) {
return true, nil
} else {
return false, nil
}
}

Comment on lines +30 to +41
accountState, found := k.GetAccountState(ctx, address)
if !found {
// initialize accountplus state with ts nonce details
k.SetAccountState(ctx, address, GetAccountPlusStateWithTimestampNonceDetails(address, tsNonce))
} else {
EjectStaleTimestampNonces(&accountState, blockTs)
tsNonceAccepted := AttemptTimestampNonceUpdate(tsNonce, &accountState)
if !tsNonceAccepted {
return fmt.Errorf("timestamp nonce %d rejected", tsNonce)
}
k.SetAccountState(ctx, address, accountState)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider logging account state initialization.

When initializing the account state, consider adding a log entry to help with debugging and monitoring.

if !found {
	// initialize accountplus state with ts nonce details
	k.SetAccountState(ctx, address, GetAccountPlusStateWithTimestampNonceDetails(address, tsNonce))
	fmt.Printf("Initialized account state for address: %s with tsNonce: %d", address, tsNonce)
} else {
	EjectStaleTimestampNonces(&accountState, blockTs)
	tsNonceAccepted := AttemptTimestampNonceUpdate(tsNonce, &accountState)
	if !tsNonceAccepted {
		return fmt.Errorf("timestamp nonce %d rejected", tsNonce)
	}
	k.SetAccountState(ctx, address, accountState)
}

Comment on lines 23 to 29
func (k Keeper) ProcessTimestampNonce(ctx sdk.Context, acc sdk.AccountI, tsNonce uint64) error {
blockTs := uint64(ctx.BlockTime().UnixMilli())
address := acc.GetAddress()

if !IsValidTimestampNonce(tsNonce, blockTs) {
return fmt.Errorf("timestamp nonce %d not within valid time window", tsNonce)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure the error message is user-friendly.

The error message "timestamp nonce %d not within valid time window" could be more user-friendly by providing additional context or guidance on acceptable time windows.

- return fmt.Errorf("timestamp nonce %d not within valid time window", tsNonce)
+ return fmt.Errorf("timestamp nonce %d not within the valid time window. Ensure the nonce is within %d ms of the current block time.", tsNonce, MaxTimeInPastMs)

Committable suggestion was skipped due to low confidence.

Comment on lines 103 to 120
start := time.Now()
err = svd.akp.ProcessTimestampNonce(ctx, acc, sig.Sequence)

if !accountpluskeeper.IsValidTimestampNonce(tsNonce, blockTs) {
return ctx, errorsmod.Wrapf(
sdkerrors.ErrWrongSequence,
"timestamp nonce %d not within valid time window", tsNonce,
telemetry.MeasureSince(start, []string{metrics.TimestampNonce, metrics.Latency}...)
if err == nil {
telemetry.IncrCounterWithLabels(
[]string{metrics.TimestampNonce, metrics.Valid, metrics.Count},
1,
[]gometrics.Label{metrics.GetLabelForIntValue(metrics.ExecMode, int(ctx.ExecMode()))},
)
}
accountState, found := svd.akp.GetAccountState(ctx, address)
if !found {
err := svd.akp.InitializeAccountWithTimestampNonceDetails(ctx, address, tsNonce)
if err != nil {
return ctx, errorsmod.Wrapf(
sdkerrors.ErrLogic,
fmt.Sprintf("failed to initialize AccountState for address %d", address),
)
}
return ctx, nil
} else {
accountpluskeeper.EjectStaleTimestampNonces(&accountState, blockTs)
tsNonceAccepted := accountpluskeeper.AttemptTimestampNonceUpdate(tsNonce, &accountState)
if !tsNonceAccepted {
return ctx, errorsmod.Wrapf(
sdkerrors.ErrWrongSequence,
"timestamp nonce %d rejected", tsNonce,
)
}
svd.akp.SetAccountState(ctx, address, accountState)
telemetry.IncrCounterWithLabels(
[]string{metrics.TimestampNonce, metrics.Invalid, metrics.Count},
1,
[]gometrics.Label{metrics.GetLabelForIntValue(metrics.ExecMode, int(ctx.ExecMode()))},
)
return ctx, errorsmod.Wrapf(sdkerrors.ErrWrongSequence, err.Error())
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider logging nonce processing duration for better monitoring.

The duration of nonce processing can be logged for better monitoring and performance analysis.

start := time.Now()
err = svd.akp.ProcessTimestampNonce(ctx, acc, sig.Sequence)
duration := time.Since(start)

telemetry.MeasureSince(start, []string{metrics.TimestampNonce, metrics.Latency}...)
if err == nil {
	telemetry.IncrCounterWithLabels(
		[]string{metrics.TimestampNonce, metrics.Valid, metrics.Count},
		1,
		[]gometrics.Label{metrics.GetLabelForIntValue(metrics.ExecMode, int(ctx.ExecMode()))},
	)
	fmt.Printf("Processed valid timestamp nonce %d in %s", sig.Sequence, duration)
	return ctx, nil
} else {
	telemetry.IncrCounterWithLabels(
		[]string{metrics.TimestampNonce, metrics.Invalid, metrics.Count},
		1,
		[]gometrics.Label{metrics.GetLabelForIntValue(metrics.ExecMode, int(ctx.ExecMode()))},
	)
	fmt.Printf("Failed to process timestamp nonce %d in %s: %s", sig.Sequence, duration, err.Error())
	return ctx, errorsmod.Wrapf(sdkerrors.ErrWrongSequence, err.Error())
}

protocol/app/ante.go Outdated Show resolved Hide resolved
Comment on lines +255 to +260
var isTimestampNonce bool
if isTimestampNonce, err = accountplusante.IsTimestampNonceTx(ctx, tx); err != nil {
return ctx, err
}

if !isShortTerm && !isTimestampNonce {
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider logging the timestamp nonce check for better debugging.

The check for timestamp nonce transactions can be logged for better debugging and monitoring.

var isTimestampNonce bool
if isTimestampNonce, err = accountplusante.IsTimestampNonceTx(ctx, tx); err != nil {
	return ctx, err
}
fmt.Printf("Transaction %s is a timestamp nonce: %t", tx.GetTxHash(), isTimestampNonce)

if !isShortTerm && !isTimestampNonce {
	if ctx, err = h.incrementSequence.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
		return ctx, err
	}
}

@jerryfan01234
Copy link
Contributor Author

Will fix typo flagged by golangcli-lint after remainder of tests finish running

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (1)
protocol/x/accountplus/keeper/timestampnonce.go (1)

31-34: Consider logging account state initialization.

When initializing the account state, consider adding a log entry to help with debugging and monitoring.

if !found {
	// initialize accountplus state with ts nonce details
	k.SetAccountState(ctx, address, GetAccountPlusStateWithTimestampNonceDetails(address, tsNonce))
+  fmt.Printf("Initialized account state for address: %s with tsNonce: %d", address, tsNonce)
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0e28134 and 5625b2e.

Files selected for processing (9)
  • protocol/app/ante.go (5 hunks)
  • protocol/app/ante/sigverify.go (4 hunks)
  • protocol/lib/metrics/constants.go (2 hunks)
  • protocol/x/accountplus/ante/timestampnonce.go (1 hunks)
  • protocol/x/accountplus/ante/timestampnonce_test.go (1 hunks)
  • protocol/x/accountplus/keeper/keeper.go (2 hunks)
  • protocol/x/accountplus/keeper/keeper_test.go (1 hunks)
  • protocol/x/accountplus/keeper/timestampnonce.go (2 hunks)
  • protocol/x/accountplus/keeper/timestampnonce_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (6)
  • protocol/app/ante.go
  • protocol/app/ante/sigverify.go
  • protocol/lib/metrics/constants.go
  • protocol/x/accountplus/ante/timestampnonce.go
  • protocol/x/accountplus/ante/timestampnonce_test.go
  • protocol/x/accountplus/keeper/timestampnonce_test.go

require.Equal(t, actualAccount, expectedAccount)
})
}
// TODO: add explicit unit tests for Get and Set funcs
Copy link
Contributor

Choose a reason for hiding this comment

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

Reduction in test coverage.

The removal of the TestInitializeAccount function reduces the current test coverage. Consider adding the new unit tests for Get and Set functions as soon as possible to maintain test coverage.

Do you want me to help create the new unit tests or open a GitHub issue to track this task?

Comment on lines +67 to +71
func GetAccountPlusStateWithTimestampNonceDetails(
address sdk.AccAddress,
tsNonce uint64,
) error {
if _, found := k.GetAccountState(ctx, address); found {
msg := "Cannot initialize AccountState for address with existing AccountState, address: " + address.String()
k.Logger(ctx).Error(msg)
return errors.New(msg)
}

accountState := types.AccountState{
) types.AccountState {
return types.AccountState{
Copy link
Contributor

Choose a reason for hiding this comment

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

Reintroduce error handling and logging.

The new method GetAccountPlusStateWithTimestampNonceDetails removes error handling and logging, which could lead to potential issues if the method is called with an address that already has an associated account state. Consider adding error handling and logging to ensure data integrity and ease of debugging.

func GetAccountPlusStateWithTimestampNonceDetails(
	address sdk.AccAddress,
	tsNonce uint64,
) types.AccountState {
+  // Add error handling and logging
+  if address == nil {
+    return types.AccountState{}, fmt.Errorf("address cannot be nil")
+  }
+  log.Printf("Generating account state for address: %s with tsNonce: %d", address.String(), tsNonce)
	return types.AccountState{
		Address: address.String(),
		TimestampNonceDetails: types.TimestampNonceDetails{
			MaxEjectedNonce: TimestampNonceSequenceCutoff,
			TimestampNonces: []uint64{tsNonce},
		},
	}
}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func GetAccountPlusStateWithTimestampNonceDetails(
address sdk.AccAddress,
tsNonce uint64,
) error {
if _, found := k.GetAccountState(ctx, address); found {
msg := "Cannot initialize AccountState for address with existing AccountState, address: " + address.String()
k.Logger(ctx).Error(msg)
return errors.New(msg)
}
accountState := types.AccountState{
) types.AccountState {
return types.AccountState{
func GetAccountPlusStateWithTimestampNonceDetails(
address sdk.AccAddress,
tsNonce uint64,
) types.AccountState {
// Add error handling and logging
if address == nil {
return types.AccountState{}, fmt.Errorf("address cannot be nil")
}
log.Printf("Generating account state for address: %s with tsNonce: %d", address.String(), tsNonce)
return types.AccountState{
Address: address.String(),
TimestampNonceDetails: types.TimestampNonceDetails{
MaxEjectedNonce: TimestampNonceSequenceCutoff,
TimestampNonces: []uint64{tsNonce},
},
}
}

Comment on lines +27 to +29
if !IsValidTimestampNonce(tsNonce, blockTs) {
return fmt.Errorf("timestamp nonce %d not within valid time window", tsNonce)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Enhance error message for timestamp nonce validation.

The error message "timestamp nonce %d not within valid time window" could be more user-friendly by providing additional context or guidance on acceptable time windows.

return fmt.Errorf("timestamp nonce %d not within valid time window", tsNonce)
+ return fmt.Errorf("timestamp nonce %d not within the valid time window. Ensure the nonce is within %d ms of the current block time.", tsNonce, MaxTimeInPastMs)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if !IsValidTimestampNonce(tsNonce, blockTs) {
return fmt.Errorf("timestamp nonce %d not within valid time window", tsNonce)
}
if !IsValidTimestampNonce(tsNonce, blockTs) {
return fmt.Errorf("timestamp nonce %d not within the valid time window. Ensure the nonce is within %d ms of the current block time.", tsNonce, MaxTimeInPastMs)
}

protocol/app/ante.go Outdated Show resolved Hide resolved
protocol/app/ante/sigverify.go Outdated Show resolved Hide resolved
protocol/app/ante/sigverify.go Outdated Show resolved Hide resolved
protocol/x/accountplus/ante/timestampnonce.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5625b2e and fe97218.

Files selected for processing (5)
  • protocol/app/ante.go (4 hunks)
  • protocol/app/ante/sigverify.go (5 hunks)
  • protocol/x/accountplus/ante/timestampnonce.go (1 hunks)
  • protocol/x/accountplus/keeper/keeper_test.go (1 hunks)
  • protocol/x/accountplus/keeper/timestampnonce_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • protocol/app/ante.go
  • protocol/app/ante/sigverify.go
  • protocol/x/accountplus/ante/timestampnonce.go
  • protocol/x/accountplus/keeper/timestampnonce_test.go

Comment on lines +3 to +4
// TODO: add explicit unit tests for Get and Set funcs
// https://linear.app/dydx/issue/OTE-633/add-explicit-unit-tests-for-get-and-set-methods-for-accountplus-keeper
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: Add explicit unit tests for Get and Set functions.

The TODO comment indicates the need to add unit tests for Get and Set functions. The removal of the TestInitializeAccount function has reduced the current test coverage.

Do you want me to help create the new unit tests or open a GitHub issue to track this task?

@@ -100,10 +99,14 @@ func (svd SigVerificationDecorator) AnteHandle(
// `GoodTilBlock` for replay protection.
if !skipSequenceValidation {
if accountpluskeeper.IsTimestampNonce(sig.Sequence) {
start := time.Now()
defer telemetry.ModuleMeasureSince(
Copy link
Contributor

Choose a reason for hiding this comment

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

This needs to be put within ProcessTimestampNonce so that the defer clause is run when ProcessTimestampNonce returns. This is a common pattern to measure the latency of a function from start to finish

Copy link
Contributor Author

Choose a reason for hiding this comment

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

				defer telemetry.ModuleMeasureSince(
					accountplustypes.ModuleName,
					time.Now(),
					metrics.TimestampNonce,
					metrics.Latency,
				)
				err = svd.akp.ProcessTimestampNonce(ctx, acc, sig.Sequence)

A bit confused. As u said defer run after the function below is run. In this case it is right above
err = svd.akp.ProcessTimestampNonce(ctx, acc, sig.Sequence)
So it will run after ProcessTimestampNonce?

Copy link
Contributor

Choose a reason for hiding this comment

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

A defer statement defers the execution of a function until the surrounding function returns. https://go.dev/tour/flowcontrol/12

@@ -1,3 +1,4 @@
package keeper_test

// TODO: add explicit unit tests for Get and Set funcs
// https://linear.app/dydx/issue/OTE-633/add-explicit-unit-tests-for-get-and-set-methods-for-accountplus-keeper
Copy link
Contributor

@teddyding teddyding Jul 26, 2024

Choose a reason for hiding this comment

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

Styling convention:

// TODO(OTE-634): add explicit unit tests for get and set methods for accountplus keeper

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between fe97218 and d866fa7.

Files selected for processing (2)
  • protocol/app/ante/sigverify.go (3 hunks)
  • protocol/x/accountplus/keeper/timestampnonce.go (2 hunks)
Files skipped from review as they are similar to previous changes (2)
  • protocol/app/ante/sigverify.go
  • protocol/x/accountplus/keeper/timestampnonce.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging this pull request may close these issues.

2 participants