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

fix init-from-state cmd #264

Closed
wants to merge 1 commit into from
Closed

Conversation

simi-dev
Copy link
Contributor

@simi-dev simi-dev commented Jan 16, 2025

Summary by CodeRabbit

  • New Features

    • Updated initialization process for Tendermint node
    • Refined validator data management logic
  • Bug Fixes

    • Adjusted validator power calculation method
    • Modified keyring service name initialization

These changes improve the node initialization and validator management process with more precise handling of configuration and power settings.

Copy link

coderabbitai bot commented Jan 16, 2025

📝 Walkthrough

Walkthrough

The pull request introduces modifications to the init_from_state.go file in the BitSong project, focusing on refining the initialization process for Tendermint nodes and validator data management. The changes include adjusting the keyring service name, updating the validator power calculation method, and implementing a more streamlined approach to handling validator updates. The core functionality remains consistent, with improvements in code clarity and data manipulation logic.

Changes

File Change Summary
cmd/bitsongd/cmd/init_from_state.go - Modified keyring initialization flag from "test" to "os"
- Refined validator data update logic
- Adjusted validator power calculation method
- Updated LastValidatorPowers handling

Poem

🐰 A Rabbit's Ode to Code Refinement 🔧

In bits and bytes, a dance so neat,
Validators' powers now complete,
From test to OS, the flag takes flight,
Refactored logic shining bright,
A code ballet of pure delight! 🚀

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.

Copy link

@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: 2

🧹 Nitpick comments (2)
cmd/bitsongd/cmd/init_from_state.go (2)

Line range hint 169-175: Address TODO comment about genesis validation.

The commented-out genesis validation code should be fixed and uncommented to ensure the generated genesis file is valid.

Would you like me to help implement the genesis validation logic or create a GitHub issue to track this task?


55-55: Add command usage example as code comment.

The command usage example is currently in an unusual location. Consider moving it to the command's description or help text.

-// bitsongd init-from-state v021 export-v021.json v021 --old-moniker Cosmostation --old-account-addr bitsong1wf3q0a3uzechxvf27reuqts8nqm45sn29ykncv  --increase-coin-amount 10000000000000000 -o
+	cmd.Example = `
+  $ bitsongd init-from-state v021 export-v021.json v021 \
+    --old-moniker Cosmostation \
+    --old-account-addr bitsong1wf3q0a3uzechxvf27reuqts8nqm45sn29ykncv \
+    --increase-coin-amount 10000000000000000 -o
+`
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bc3863e and db1cd34.

📒 Files selected for processing (1)
  • cmd/bitsongd/cmd/init_from_state.go (4 hunks)
🔇 Additional comments (1)
cmd/bitsongd/cmd/init_from_state.go (1)

117-117: Verify the impact of changing keyring backend from "test" to "os".

The change from "test" to "os" backend improves security but requires user interaction for key operations. This might affect automation scripts or CI/CD pipelines that previously relied on the non-interactive "test" backend.

Run this script to check for potential automation dependencies:

✅ Verification successful

✓ Keyring backend change to "os" is appropriate

The change to use the "os" backend is safe as this command is designed for manual operations and isn't used in any automated processes or tests. The improved security from using the OS's credential store is beneficial for this use case.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for automation scripts that might be affected by the keyring backend change

# Look for CI/CD files that might use this command
rg -g '*.{yml,yaml}' -A 5 'init-from-state'

# Look for shell scripts that might use this command
rg -g '*.sh' -A 5 'init-from-state'

Length of output: 79


Script:

#!/bin/bash
# Search for any usage of init-from-state command
rg -l "InitFromState"

# Search for keyring initialization patterns
rg -A 3 'keyring\.New\(' 

# Look for test files that might use keyring
fd -e test.go --exec grep -l "keyring"

Length of output: 501

Comment on lines +401 to +408
// Update LastValidatorPowers
stakingGenState.LastValidatorPowers = []stakingtypes.LastValidatorPower{
{
Address: operatorAddr,
Power: updatedValidators[0].Power,
},
}
stakingGenState.LastTotalPower = stakingGenState.LastTotalPower.Add(sdk.NewInt(params.IncreaseCoinAmount / 1000000))

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix potential panic in LastValidatorPowers update.

The code assumes updatedValidators has exactly one element and directly accesses index 0, which could panic if the slice is empty.

Apply this safer implementation:

-	stakingGenState.LastValidatorPowers = []stakingtypes.LastValidatorPower{
-		{
-			Address: operatorAddr,
-			Power:   updatedValidators[0].Power,
-		},
-	}
+	if len(updatedValidators) == 0 {
+		return nil, fmt.Errorf("no validator found with moniker %s", params.OldMoniker)
+	}
+	stakingGenState.LastValidatorPowers = []stakingtypes.LastValidatorPower{{
+		Address: operatorAddr,
+		Power:   updatedValidators[0].Power,
+	}}
📝 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
// Update LastValidatorPowers
stakingGenState.LastValidatorPowers = []stakingtypes.LastValidatorPower{
{
Address: operatorAddr,
Power: updatedValidators[0].Power,
},
}
stakingGenState.LastTotalPower = stakingGenState.LastTotalPower.Add(sdk.NewInt(params.IncreaseCoinAmount / 1000000))
if len(updatedValidators) == 0 {
return nil, fmt.Errorf("no validator found with moniker %s", params.OldMoniker)
}
stakingGenState.LastValidatorPowers = []stakingtypes.LastValidatorPower{{
Address: operatorAddr,
Power: updatedValidators[0].Power,
}}

Comment on lines +349 to +368
// Filter the validators to keep only the one matching params.OldMoniker
var updatedValidators []tmtypes.GenesisValidator
for i := range genDoc.Validators {
if genDoc.Validators[i].Name == params.OldMoniker {
oldValidator = genDoc.Validators[i]
// Update the matching validator's data
validator := &genDoc.Validators[i]

// Replace validator data
validator.PubKey = params.TmPubKey
validator.Address = params.TmPubKey.Address()
validator.Power = validator.Power + (params.IncreaseCoinAmount / 1000000)
validator.Power = validator.Power + (params.IncreaseCoinAmount)

// Add the updated validator to the new slice
updatedValidators = append(updatedValidators, *validator)
break // Exit loop after finding and updating the matching validator
}
}

// Replace the original validators slice with the updated slice
genDoc.Validators = updatedValidators
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve validator update logic to handle edge cases.

The current implementation has several potential issues:

  1. It assumes only one validator matches the moniker, breaking after the first match.
  2. Using a single-element slice in updatedValidators could be problematic if multiple validators share the same moniker.
  3. The power calculation no longer divides by 1,000,000, which might affect compatibility.

Consider this safer implementation:

-	var updatedValidators []tmtypes.GenesisValidator
+	updatedValidators := make([]tmtypes.GenesisValidator, 0)
 	for i := range genDoc.Validators {
 		if genDoc.Validators[i].Name == params.OldMoniker {
 			oldValidator = genDoc.Validators[i]
-			// Update the matching validator's data
 			validator := &genDoc.Validators[i]
 
 			validator.PubKey = params.TmPubKey
 			validator.Address = params.TmPubKey.Address()
-			validator.Power = validator.Power + (params.IncreaseCoinAmount)
+			validator.Power = validator.Power + (params.IncreaseCoinAmount / 1_000_000)
 
-			// Add the updated validator to the new slice
 			updatedValidators = append(updatedValidators, *validator)
-			break // Exit loop after finding and updating the matching validator
+			if len(updatedValidators) > 1 {
+				return nil, fmt.Errorf("multiple validators found with moniker %s", params.OldMoniker)
+			}
 		}
 	}
📝 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
// Filter the validators to keep only the one matching params.OldMoniker
var updatedValidators []tmtypes.GenesisValidator
for i := range genDoc.Validators {
if genDoc.Validators[i].Name == params.OldMoniker {
oldValidator = genDoc.Validators[i]
// Update the matching validator's data
validator := &genDoc.Validators[i]
// Replace validator data
validator.PubKey = params.TmPubKey
validator.Address = params.TmPubKey.Address()
validator.Power = validator.Power + (params.IncreaseCoinAmount / 1000000)
validator.Power = validator.Power + (params.IncreaseCoinAmount)
// Add the updated validator to the new slice
updatedValidators = append(updatedValidators, *validator)
break // Exit loop after finding and updating the matching validator
}
}
// Replace the original validators slice with the updated slice
genDoc.Validators = updatedValidators
// Filter the validators to keep only the one matching params.OldMoniker
updatedValidators := make([]tmtypes.GenesisValidator, 0)
for i := range genDoc.Validators {
if genDoc.Validators[i].Name == params.OldMoniker {
oldValidator = genDoc.Validators[i]
validator := &genDoc.Validators[i]
validator.PubKey = params.TmPubKey
validator.Address = params.TmPubKey.Address()
validator.Power = validator.Power + (params.IncreaseCoinAmount / 1_000_000)
updatedValidators = append(updatedValidators, *validator)
if len(updatedValidators) > 1 {
return nil, fmt.Errorf("multiple validators found with moniker %s", params.OldMoniker)
}
}
}
// Replace the original validators slice with the updated slice
genDoc.Validators = updatedValidators

@hard-nett
Copy link
Contributor

merged in #265 , will be replaced for new function from sdk to generate-testnet from state from state

@hard-nett hard-nett closed this Feb 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants