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

feat: add multi-account support #3433

Merged
merged 26 commits into from
May 24, 2024
Merged

feat: add multi-account support #3433

merged 26 commits into from
May 24, 2024

Conversation

cmwaters
Copy link
Contributor

@cmwaters cmwaters commented May 6, 2024

Closes: #3259

This PR adds support for using multiple kerying keys with a single Signer. It splits signer into a purely offline signer for signing messages and the txclient responsible for tx submission and handling

Comment on lines 148 to 151
accNum, seqNum, err := QueryAccount(ctx, conn, encCfg.InterfaceRegistry, addr)
if err != nil {
return nil, fmt.Errorf("querying account: %w", err)
}
Copy link
Member

Choose a reason for hiding this comment

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

just to record something, this mech forces each key in the keyring to also be an account with state. In general, this is a desired behavior, however if a user adds a new key to the keyring, now they will be unable setup the txclient

Copy link
Contributor Author

Choose a reason for hiding this comment

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

They should be able to add keys after setting up the tx client. If it's the first time the key is being used, the txclient will automatically query for the sequence number etc... before submitting the transactions.

@cmwaters cmwaters marked this pull request as ready for review May 21, 2024 16:10
@cmwaters cmwaters requested a review from rach-id as a code owner May 21, 2024 16:10
@cmwaters cmwaters requested review from rootulp and evan-forbes and removed request for a team May 21, 2024 16:10
Copy link
Contributor

coderabbitai bot commented May 21, 2024

Walkthrough

The changes involve updating various test files and the Makefile to improve transaction handling, error management, and account management within a Cosmos SDK application. The modifications include refactoring the creation and use of signers, introducing a TxClient for transaction management, and enhancing error handling in blob transactions.

Changes

File(s) Change Summary
Makefile Updated the test-race target to exclude TestTxClientTestSuite.
app/errors/insufficient_gas_price_test.go, app/errors/nonce_mismatch_test.go, app/test/big_blob_test.go, app/test/check_tx_test.go, app/test/integration_test.go, app/test/prepare_proposal_context_test.go, app/test/priority_test.go, app/test/process_proposal_test.go, app/test/square_size_test.go, app/test/std_sdk_test.go Refactored signer creation and transaction handling methods.
pkg/proof/proof_test.go Updated NewShareInclusionProof test cases with new startingShare and endingShare values.
pkg/user/account.go Introduced Account struct and methods for account management.
pkg/user/e2e_test.go Renamed signer to txClient and updated transaction submission methods.
pkg/user/signer.go Refactored Signer struct and methods, removing old fields and adding new account management features.
pkg/user/tx_client.go Introduced TxClient type for managing transactions, with methods for submitting and broadcasting transactions.
pkg/user/tx_client_test.go Renamed SignerTestSuite to TxClientTestSuite and updated related functions.
test/util/blobfactory/payforblob_factory.go, test/util/blobfactory/payforblob_factory_test.go Updated methods to use new signer and transaction handling logic.
x/blob/types/blob_tx_test.go, x/blob/types/estimate_gas_test.go, x/blob/types/payforblob.go, x/blob/types/payforblob_test.go Refactored account handling and error management in blob transaction tests.

Assessment against linked issues

Objective (Issue #3259) Addressed Explanation
Support multiple keys within signer
Allow submitting sdk.Msgs with different accounts
Introduce optional argument for providing the signer in PFBs
Ensure the signer can read from the transaction and check the keyring
Do not support transactions with multiple signers (rare requirement)

The changes comprehensively address the objectives from the linked issue by enhancing the Signer to support multiple keys, allowing transactions to be signed with different accounts, and adding functional options for transaction management.


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:

Note: Auto-reply has been disabled for this repository by the repository owner. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

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

CodeRabbit Configration 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
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: 13

Outside diff range and nitpick comments (2)
pkg/user/signer.go (1)

Line range hint 88-110: Improve error handling and messaging in CreatePayForBlobs.

The CreatePayForBlobs method could improve its error handling by providing more detailed error messages, especially when an account is not found or when there are issues with transaction signing or encoding. Consider enhancing the error messages to include more context about the operation being performed and the specific failure point.

test/util/testnode/node_interaction_api.go (1)

Line range hint 242-255: Refactor the PostData method to use the new TxClient for transaction submission.

- signer, err := user.NewSigner(c.Keyring, c.TxConfig, c.ChainID, appconsts.LatestVersion, user.NewAccount(account, acc, seq))
+ txClient, err := user.NewTxClient(c.Keyring, c.TxConfig, c.ChainID, appconsts.LatestVersion, user.NewAccount(account, acc, seq))
  if err != nil {
    return nil, err
  }

- blobTx, _, err := signer.CreatePayForBlobs(account, []*blob.Blob{b}, opts...)
+ blobTx, _, err := txClient.CreatePayForBlobs(account, []*blob.Blob{b}, opts...)
  if err != nil {
    return nil, err
  }

This change aligns the PostData method with the new architecture where TxClient handles transaction submissions, improving consistency and leveraging the new capabilities of TxClient.

Comment on lines +18 to +33
// Signer is struct for building and signing Celestia transactions
// It supports multiple accounts wrapping a Keyring.
// NOTE: All transactions may only have a single signer
// Signer is not thread-safe.
type Signer struct {
keys keyring.Keyring
address sdktypes.AccAddress
enc client.TxConfig
grpc *grpc.ClientConn
pk cryptotypes.PubKey
chainID string
accountNumber uint64
keys keyring.Keyring
enc client.TxConfig
chainID string
// FIXME: the signer is currently incapable of detecting an appversion
// change and could produce incorrect PFBs if it the network is at an
// appVersion that the signer does not support
appVersion uint64

mtx sync.RWMutex
// how often to poll the network for confirmation of a transaction
pollTime time.Duration
// the signers local view of the sequence number
localSequence uint64
// the chains last known sequence number
networkSequence uint64
// gasMultiplier is used to increase gas limit as it is sometimes underestimated
gasMultiplier float64
// lookup map of all pending and yet to be confirmed outbound transactions
outboundSequences map[uint64]struct{}
// a reverse map for confirming which sequence numbers have been committed
reverseTxHashSequenceMap map[string]uint64
// set of accounts that the signer can manage. Should match the keys on the keyring
accounts map[string]*Account
addressToAccountMap map[string]string
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor the Signer struct to handle app version changes dynamically.

The current implementation of the Signer struct includes a FIXME comment about its inability to handle app version changes dynamically. This could lead to incorrect transaction signing if the app version changes. Consider implementing a mechanism to update the appVersion dynamically or fetch it as needed to ensure the Signer remains accurate across version changes.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Turned this into an issue because I don't believe we have one currently

pkg/user/signer.go Show resolved Hide resolved
pkg/user/signer.go Show resolved Hide resolved
Comment on lines +418 to +434
func (s *TxClient) checkAccountLoaded(ctx context.Context, account string) error {
if _, exists := s.signer.accounts[account]; exists {
return nil
}
record, err := s.signer.keys.Key(account)
if err != nil {
return fmt.Errorf("trying to find account %s on keyring: %w", account, err)
}
addr, err := record.GetAddress()
if err != nil {
return fmt.Errorf("retrieving address from keyring: %w", err)
}
accNum, sequence, err := QueryAccount(ctx, s.grpc, s.registry, addr)
if err != nil {
return fmt.Errorf("querying account %s: %w", account, err)
}
return s.signer.AddAccount(NewAccount(account, accNum, sequence))
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize account checking and querying logic.

This function performs multiple operations that could be streamlined. For example, querying the account could be moved to a separate method to improve readability and reusability.

+ func (s *TxClient) queryAccount(ctx context.Context, account string) error {
+     // Implementation of account querying logic
+ }
-	accNum, sequence, err := QueryAccount(ctx, s.grpc, s.registry, addr)
+	err := s.queryAccount(ctx, account)

Committable suggestion was skipped due low confidence.

Comment on lines +45 to +52
func WithDefaultAddress(address sdktypes.AccAddress) Option {
return func(c *TxClient) {
record, err := c.signer.keys.KeyByAddress(address)
if err != nil {
panic(err)
}
c.defaultAccount = record.Name
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider handling errors more gracefully instead of using panic.

Using panic for error handling in production code, especially in a library, can lead to abrupt termination of applications that use this library. It would be better to return an error and let the caller decide how to handle it.

-			panic(err)
+			return nil, err

Committable suggestion was skipped due low confidence.

pkg/user/tx_client.go Show resolved Hide resolved
pkg/user/tx_client.go Show resolved Hide resolved
test/util/blobfactory/payforblob_factory.go Show resolved Hide resolved
Comment on lines +38 to +43
txClient *user.TxClient
balance uint64
latestHeight uint64
lastUpdated time.Time
subaccounts map[string]*user.Signer
accountIndex int
addressMap map[string]string
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor to use the new TxClient for transaction management.

- am.txClient, err = user.SetupTxClient(ctx, am.keys, am.conn, am.encCfg, user.WithDefaultAccount(masterAccName), user.WithPollTime(am.pollTime))
+ txClient, err := user.NewTxClient(ctx, am.keys, am.conn, am.encCfg, user.WithDefaultAccount(masterAccName), user.WithPollTime(am.pollTime))
  if err != nil {
    return err
  }
  am.txClient = txClient

This change updates the AccountManager to instantiate a TxClient using the new constructor, aligning with the updated transaction management architecture.

Also applies to: 149-155, 175-186, 213-214, 239-239, 247-257, 282-282


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.

Suggested change
txClient *user.TxClient
balance uint64
latestHeight uint64
lastUpdated time.Time
subaccounts map[string]*user.Signer
accountIndex int
addressMap map[string]string
txClient, err := user.NewTxClient(ctx, am.keys, am.conn, am.encCfg, user.WithDefaultAccount(masterAccName), user.WithPollTime(am.pollTime))
if err != nil {
return err
}
am.txClient = txClient

Comment on lines +314 to +317
msgs, signer := tt.msgFunc()
txClient, err := user.SetupTxClient(s.cctx.GoContext(), s.cctx.Keyring, s.cctx.GRPCClient, s.ecfg, user.WithDefaultAccount(signer))
require.NoError(t, err)
res, err := signer.SubmitTx(s.cctx.GoContext(), msgs, blobfactory.DefaultTxOpts()...)
res, err := txClient.SubmitTx(s.cctx.GoContext(), msgs, blobfactory.DefaultTxOpts()...)
Copy link
Contributor

Choose a reason for hiding this comment

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

Update the test setup to use the new TxClient.

- txClient, err := user.SetupTxClient(s.cctx.GoContext(), s.cctx.Keyring, s.cctx.GRPCClient, s.ecfg, user.WithDefaultAccount(signer))
+ txClient, err := user.NewTxClient(s.cctx.GoContext(), s.cctx.Keyring, s.cctx.GRPCClient, s.ecfg, user.WithDefaultAccount(signer))
  require.NoError(t, err)

This change ensures that the test suite uses the new TxClient constructor, maintaining consistency with the updated transaction management system.


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.

Suggested change
msgs, signer := tt.msgFunc()
txClient, err := user.SetupTxClient(s.cctx.GoContext(), s.cctx.Keyring, s.cctx.GRPCClient, s.ecfg, user.WithDefaultAccount(signer))
require.NoError(t, err)
res, err := signer.SubmitTx(s.cctx.GoContext(), msgs, blobfactory.DefaultTxOpts()...)
res, err := txClient.SubmitTx(s.cctx.GoContext(), msgs, blobfactory.DefaultTxOpts()...)
msgs, signer := tt.msgFunc()
txClient, err := user.NewTxClient(s.cctx.GoContext(), s.cctx.Keyring, s.cctx.GRPCClient, s.ecfg, user.WithDefaultAccount(signer))
require.NoError(t, err)
res, err := txClient.SubmitTx(s.cctx.GoContext(), msgs, blobfactory.DefaultTxOpts()...)

rootulp
rootulp previously approved these changes May 21, 2024
app/test/check_tx_test.go Outdated Show resolved Hide resolved
app/test/check_tx_test.go Outdated Show resolved Hide resolved
Comment on lines +197 to +198
startingShare: 56,
endingShare: 58,
Copy link
Collaborator

Choose a reason for hiding this comment

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

[no change needed] do you have any idea why these blob shares got move over by one share? Perhaps something in the tx namespace occupied one extra share?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah I was actually curious that this needed to change. I looked through the code and couldn't see why the PFBs would take up more space. One thing I think we should add if we don't have already is regression tests to the square / share construction to make sure that breaking changes are caught

pkg/user/signer.go Outdated Show resolved Hide resolved
x/blob/types/estimate_gas_test.go Outdated Show resolved Hide resolved
evan-forbes
evan-forbes previously approved these changes May 21, 2024
Copy link
Member

@evan-forbes evan-forbes left a comment

Choose a reason for hiding this comment

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

nice! its been cool to see this code evolve. can't wait to play with it

@cmwaters cmwaters dismissed stale reviews from evan-forbes and rootulp via 6a36f1d May 22, 2024 08:06
@celestia-bot celestia-bot requested a review from a team May 22, 2024 08:06
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: 4

pkg/user/signer.go Show resolved Hide resolved
pkg/user/signer.go Show resolved Hide resolved
pkg/user/signer.go Show resolved Hide resolved
pkg/user/signer.go Show resolved Hide resolved
@celestia-bot celestia-bot requested review from a team and ninabarbakadze and removed request for a team May 24, 2024 05:54
@cmwaters cmwaters merged commit 1f45486 into main May 24, 2024
32 of 33 checks passed
@cmwaters cmwaters deleted the cal/multi-accounts branch May 24, 2024 07:13
Wondertan pushed a commit to celestiaorg/celestia-node that referenced this pull request Aug 7, 2024
Update celestia-node to use celestia-app v2.0.0. A few changes that were needed:
- celestia-app v1.x had a shares package. celestia-app v2.x uses the shares package from go-square.
- celestia-app v1.x had a blob.types package with `CreateCommitment`. celestia-app v2.x uses `CreateCommitment` from the go-square inclusion package.
- I had to update extended header verification to allow `header.Version.App = 2`. Added unit tests.
- celestia-app v1.x had a lot of functionality included in the `signer`. celestia-app v2.x split a `txClient` from the `signer`. See: celestiaorg/celestia-app#3433
- ~~I had to update `core_access.go` a lot. Mostly inspired by #3451


## Testing

I ran a [script](https://gist.github.com/rootulp/73ee382b4d533cb9da27fc675e9047c0) with: celestia-app v2.0.0-rc2  and configured it to upgrade at block height 3. celestia-node (built from this PR) continued to work:

```
2024-07-09T18:13:27.040-0400	INFO	header/store	store/store.go:367	new head	{"height": 2, "hash": "8776AEAF4114BD7E88E8DEC38445720D0BD857335BED99649957A43BB845EC87"}
2024-07-09T18:13:38.065-0400	INFO	header/store	store/store.go:367	new head	{"height": 3, "hash": "63D5C64521A964290BD21658314DDF60146AE419FE99026003048F74D2886B35"}
2024-07-09T18:13:49.093-0400	INFO	header/store	store/store.go:367	new head	{"height": 4, "hash": "FC7900918E716697A7CD6D9A4865B261F3E71D181F366E765AA53CF475223F9A"}
```
sebasti810 pushed a commit to sebasti810/celestia-node that referenced this pull request Aug 14, 2024
Update celestia-node to use celestia-app v2.0.0. A few changes that were needed:
- celestia-app v1.x had a shares package. celestia-app v2.x uses the shares package from go-square.
- celestia-app v1.x had a blob.types package with `CreateCommitment`. celestia-app v2.x uses `CreateCommitment` from the go-square inclusion package.
- I had to update extended header verification to allow `header.Version.App = 2`. Added unit tests.
- celestia-app v1.x had a lot of functionality included in the `signer`. celestia-app v2.x split a `txClient` from the `signer`. See: celestiaorg/celestia-app#3433
- ~~I had to update `core_access.go` a lot. Mostly inspired by celestiaorg#3451


## Testing

I ran a [script](https://gist.github.com/rootulp/73ee382b4d533cb9da27fc675e9047c0) with: celestia-app v2.0.0-rc2  and configured it to upgrade at block height 3. celestia-node (built from this PR) continued to work:

```
2024-07-09T18:13:27.040-0400	INFO	header/store	store/store.go:367	new head	{"height": 2, "hash": "8776AEAF4114BD7E88E8DEC38445720D0BD857335BED99649957A43BB845EC87"}
2024-07-09T18:13:38.065-0400	INFO	header/store	store/store.go:367	new head	{"height": 3, "hash": "63D5C64521A964290BD21658314DDF60146AE419FE99026003048F74D2886B35"}
2024-07-09T18:13:49.093-0400	INFO	header/store	store/store.go:367	new head	{"height": 4, "hash": "FC7900918E716697A7CD6D9A4865B261F3E71D181F366E765AA53CF475223F9A"}
```
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.

Support multiple keys within signer
4 participants