-
Notifications
You must be signed in to change notification settings - Fork 0
Refactor v3.2.2 #55
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
base: test_rabbit
Are you sure you want to change the base?
Refactor v3.2.2 #55
Conversation
* Fix stuck leader when cosigner goes down * Use ticker with reset instead of timer * Fix local cosigner getnonce * lint
…west (strangelove-ventures#234) * Reverse where we start checking for a non-expired nonce, oldest -> newest * Improve TestNonceCacheExpiration * lint fix * Fix unit test * Add a little more breathing room for unit test
* mitigate unexpected state remove ClearAllNonces * use string constant
…into refactor_v3.2.2
|
Important Auto Review SkippedAuto reviews are disabled on base/target branches other than the default branch. Please add the base/target branch pattern to the list of additional branches to be reviewed in the settings. Please check the settings in the CodeRabbit UI or the To trigger a single review, invoke the WalkthroughThe codebase has undergone a significant refactor, primarily involving changes to package names and structures, aiming for better clarity and organization. The Changes
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? TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Additionally, you can add CodeRabbit Configration File (
|
|
@coderabbitai review |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 0
Configuration used: CodeRabbit UI
Files ignored due to filter (2)
- test/go.mod
- test/go.sum
Files selected for processing (44)
- .golangci.yml (1 hunks)
- cmd/horcrux/cmd/address.go (5 hunks)
- cmd/horcrux/cmd/config.go (6 hunks)
- cmd/horcrux/cmd/leader_election.go (2 hunks)
- cmd/horcrux/cmd/migrate.go (4 hunks)
- cmd/horcrux/cmd/root.go (2 hunks)
- cmd/horcrux/cmd/shards.go (7 hunks)
- cmd/horcrux/cmd/start.go (4 hunks)
- cmd/horcrux/cmd/threshold.go (4 hunks)
- pkg/config/config.go (3 hunks)
- pkg/config/config_test.go (27 hunks)
- pkg/connector/remote_signer.go (4 hunks)
- pkg/connector/remote_signer_grpc_server.go (6 hunks)
- pkg/metrics/metrics.go (4 hunks)
- pkg/nodes/cosigner.go (3 hunks)
- pkg/nodes/cosigner_security.go (1 hunks)
- pkg/nodes/local_cosigner.go (19 hunks)
- pkg/nodes/local_cosigner_test.go (10 hunks)
- pkg/nodes/nodesecurity/cosigner_key_shares.go (2 hunks)
- pkg/nodes/nodesecurity/cosigner_security_ecies.go (4 hunks)
- pkg/nodes/nodesecurity/cosigner_security_ecies_test.go (6 hunks)
- pkg/nodes/nodesecurity/cosigner_security_rsa.go (4 hunks)
- pkg/nodes/nodesecurity/cosigner_security_rsa_test.go (4 hunks)
- pkg/nodes/remote_cosigner.go (6 hunks)
- pkg/thresholdTemP/cosigner_key.go (2 hunks)
- pkg/thresholdTemP/threshold_signer.go (1 hunks)
- pkg/thresholdTemP/threshold_signer_soft.go (3 hunks)
- pkg/types/block.go (1 hunks)
- pkg/types/sign_state.go (2 hunks)
- signer/cosigner_grpc_server.go (5 hunks)
- signer/cosigner_health.go (5 hunks)
- signer/cosigner_health_test.go (1 hunks)
- signer/cosigner_nonce_cache.go (12 hunks)
- signer/cosigner_nonce_cache_test_go.txt (1 hunks)
- signer/leader_mock_test.go (2 hunks)
- signer/raft_store.go (2 hunks)
- signer/raft_store_test.go (2 hunks)
- signer/single_signer_validator.go (2 hunks)
- signer/single_signer_validator_test.go (5 hunks)
- signer/threshold_validator.go (26 hunks)
- signer/threshold_validator_test_go.txt (20 hunks)
- test/horcrux_test.go (8 hunks)
- test/validator_single.go (3 hunks)
- test/validator_threshold.go (4 hunks)
…k.go, and use block.ToHRST() in threshold_validator.go
Update package tss to use Ed25519Key instead of CosignerEd25519Key Update package config to include default values for nouncecahce Update package types to fix comment formatting Update package signer to use Ed25519Key instead of CosignerEd25519Key Update package cosigner to fix typo in comments and add MPC struct Update test files to use Ed25519Key instead of CosignerEd25519Key Update cmd files to use CreatePersistentEd25519ThresholdSignShardsFromFile instead of CreateEd25519ThresholdSignShardsFromFile Update test files to use Ed25519Key instead of CosignerEd25519Key
|
@coderabbitai review |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 8
Configuration used: CodeRabbit UI
Files selected for processing (49)
- cmd/horcrux/cmd/address.go (5 hunks)
- cmd/horcrux/cmd/config.go (6 hunks)
- cmd/horcrux/cmd/leader_election.go (2 hunks)
- cmd/horcrux/cmd/migrate.go (6 hunks)
- cmd/horcrux/cmd/shards.go (7 hunks)
- cmd/horcrux/cmd/start.go (4 hunks)
- cmd/horcrux/cmd/threshold.go (4 hunks)
- pkg/config/config.go (3 hunks)
- pkg/connector/privvalidator.go (1 hunks)
- pkg/connector/sentry_signer.go (12 hunks)
- pkg/connector/sentry_signer_grpc_server.go (9 hunks)
- pkg/cosigner/cosigner.go (4 hunks)
- pkg/cosigner/icosigner_security.go (1 hunks)
- pkg/cosigner/ithresholdsigner.go (1 hunks)
- pkg/cosigner/local_cosigner.go (19 hunks)
- pkg/cosigner/local_cosigner_test.go (10 hunks)
- pkg/cosigner/nodesecurity/cosigner_key_shares.go (2 hunks)
- pkg/cosigner/nodesecurity/cosigner_security_ecies.go (4 hunks)
- pkg/cosigner/nodesecurity/cosigner_security_ecies_test.go (6 hunks)
- pkg/cosigner/nodesecurity/cosigner_security_rsa.go (4 hunks)
- pkg/cosigner/nodesecurity/cosigner_security_rsa_test.go (4 hunks)
- pkg/cosigner/remote_cosigner.go (6 hunks)
- pkg/metrics/metrics.go (4 hunks)
- pkg/tss/godoc.go (1 hunks)
- pkg/tss/threshold-ed25519_signer_soft.go (4 hunks)
- pkg/tss/threshold_signer.go (1 hunks)
- pkg/tss/types.go (1 hunks)
- pkg/types/block.go (3 hunks)
- pkg/types/hrs.go (2 hunks)
- pkg/types/serialization.go (1 hunks)
- pkg/types/sign_state.go (11 hunks)
- signer/cosigner_grpc_server.go (6 hunks)
- signer/cosigner_health.go (5 hunks)
- signer/cosigner_health_test.go (1 hunks)
- signer/cosigner_nonce_cache.go (12 hunks)
- signer/icosigner.go (1 hunks)
- signer/leader.go (1 hunks)
- signer/leader_mock_test.go (1 hunks)
- signer/multiresolver/multi_test.go (1 hunks)
- signer/raft_events.go (1 hunks)
- signer/raft_store.go (6 hunks)
- signer/raft_store_test.go (2 hunks)
- signer/single_signer_validator.go (2 hunks)
- signer/threshold_validator.go (31 hunks)
- signer/threshold_validator_test.go.txt (10 hunks)
- test/horcrux_test.go (13 hunks)
- test/validator.go (2 hunks)
- test/validator_single.go (5 hunks)
- test/validator_threshold.go (7 hunks)
Files skipped from review due to trivial changes (5)
- pkg/cosigner/icosigner_security.go
- pkg/tss/godoc.go
- signer/leader.go
- test/validator.go
- test/validator_single.go
Additional comments: 213
pkg/connector/privvalidator.go (1)
- 10-16: The interface
IPrivValidatoris well-defined with essential methods for signing, retrieving the public key, and stopping the validator. This aligns with the principle of interface segregation.pkg/cosigner/ithresholdsigner.go (1)
- 5-16: The interface
IThresholdSigneris well-defined with methods that encapsulate the functionality of a threshold signer, including getting the public key, signing payloads, and combining signatures.signer/leader_mock_test.go (1)
- 13-41: The mock implementations
MockThresholdValidatorandMockLeaderare correctly defined for testing purposes. They implement the necessary interfaces and provide stubbed methods that can be used in unit tests.signer/raft_events.go (1)
- 43-43: The change from
f.thresholdValidatortof.mycosignerin thehandleLSSEventmethod should be verified to ensure that it aligns with the intended functionality and thatf.mycosignerhas theSaveLastSignedStatemethod with the same signature and expected behavior.signer/icosigner.go (1)
- 12-42: The interface
ICosigneris well-defined with methods that encapsulate the functionality of a cosigner, including index retrieval, address retrieval, public key retrieval, signature verification, nonce retrieval, and signing.pkg/types/serialization.go (1)
- 28-43: The change in the
UnpackHRSTfunction to return anHRSTstruct instead of anHRSTKeyshould be verified to ensure that all usages of this function have been updated accordingly to handle the new return type.pkg/types/hrs.go (1)
- 28-66: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [7-58]
The renaming of
HRSKeytoHRSandHRSTKeytoHRST, along with the updates to associated methods and functions, should be verified to ensure that all references to these types have been updated throughout the codebase to prevent any type mismatches or compilation errors.signer/cosigner_health_test.go (1)
- 14-61: The changes in the test file, including the use of mock types and the update to the
NewCosignerHealthfunction to take a slice ofICosigner, should be verified to ensure that the tests still pass and the behavior remains consistent with the expected outcomes.pkg/tss/threshold_signer.go (1)
- 11-61: The functions
LoadVaultKeyFromFileandgeneratePersistentThresholdSignShardsare correctly implemented to handle the loading and creation of threshold signer keys. Ensure that error handling is properly implemented and that the keys are securely managed.pkg/cosigner/nodesecurity/cosigner_key_shares.go (1)
- 1-11: The package name change to "nodesecurity" and the removal of certain functions should be verified to ensure that the refactoring is consistent with the intended design and that all necessary functionality is preserved.
signer/cosigner_health.go (1)
- 80-98: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [9-95]
The changes to use the
connectorpackage and modify types and method receivers fromCosignertoICosigner, andLeadertoILeader, should be verified to ensure that they are consistent with the intended refactoring and that all references and usages are correctly updated.signer/raft_store_test.go (1)
- 30-65: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [1-65]
The updates to the test file, including new package imports and the use of new functions for creating
cosignerandRaftStoreinstances, should be verified to ensure that the tests still pass and the behavior remains consistent with the expected outcomes.cmd/horcrux/cmd/start.go (1)
- 45-60: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [7-77]
The changes to use the
connectorpackage and replace references to thesignerpackage instart.goshould be verified to ensure that they are consistent with the intended refactoring and that all functionality related to gRPC server initialization and handling is correctly implemented.signer/multiresolver/multi_test.go (1)
- 42-42: The replacement of the
NewCosignerGRPCServerfunction with theNewNodeGRPCServerfunction in the registration of a gRPC server should be verified to ensure that it aligns with the intended functionality and that theNewNodeGRPCServerfunction provides the necessary implementations for the gRPC server.pkg/cosigner/nodesecurity/cosigner_security_rsa_test.go (1)
- 1-22: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [1-63]
The updates to the test file, including the use of the
nodesecuritypackage and the introduction of thebitSizeconstant, should be verified to ensure that the tests still pass and the behavior remains consistent with the expected outcomes.cmd/horcrux/cmd/address.go (1)
- 46-58: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [13-74]
The changes to replace the
signerpackage withcconfigandtsspackages inaddress.goshould be verified to ensure that they are consistent with the intended refactoring and that all cryptographic signing and key management functionalities are correctly implemented.signer/single_signer_validator.go (3)
10-12: The import paths have been updated to reflect the new package structure. Ensure that the new paths are correct and that the packages exist at the specified locations.
21-21: The type of the
configfield inSingleSignerValidatorhas been updated to use a pointer from theconfigpackage. Verify that all instances and usages ofSingleSignerValidatorhave been updated to pass the correct type.37-37: The parameter type of the
NewSingleSignerValidatorfunction has been updated to*config.RuntimeConfig. Confirm that all calls to this function have been modified to pass the correct type.pkg/types/block.go (4)
8-9: New imports for
cometprotoandcomethave been added. Confirm that these packages are used in the new methods and types introduced in this file.4-21: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [19-24]
Introduced a new
Blocktype with fieldsHeight,Round,Step,SignBytes, andTimestamp. Ensure that the new type is integrated correctly throughout the codebase and that all related functionality has been updated to use this new type.
66-71: Defined new constants
StepPropose,StepPrevote,StepPrecommit, andblocksTocache. Verify that these constants are used consistently and correctly throughout the codebase.86-91: Added new functions such as
CanonicalVoteToStep,VoteToStep,VoteToBlock,ProposalToStep,ProposalToBlock, andStepToType. Ensure that these functions are implemented correctly and are used where necessary.pkg/cosigner/cosigner.go (4)
1-1: The package has been renamed from
signertocosigner. Confirm that this change is reflected throughout the codebase and that all references to this package have been updated.20-21: The
Cosignerinterface and its associated methods have been removed. Verify that all usages of this interface have been replaced with the appropriate new types or interfaces.21-28: Introduced new types such as
MPC,LocalCosigner,RemoteCosigner,CosignerNonces, andCosignerUUIDNoncesMultiple. Ensure that these types are correctly implemented and integrated into the codebase.136-136: The
CosignerSetNoncesAndSignRequesttype now usestypes.HRSTinstead oftypes.HRSTKey. Confirm that all instances where this type is used have been updated to accommodate the new field type.cmd/horcrux/cmd/threshold.go (2)
20-32: Added new functions
CosignerSecurityECIESandCosignerSecurityRSAfor creating ECIES and RSA cosigner security instances. Verify that these functions are implemented correctly and that error handling is appropriate.59-69: The
NewThresholdValidatorfunction has been refactored to use the new cosigner interfaces and implementations. Ensure that the initialization of remote and local cosigners is correct and that the new security instances are integrated properly.pkg/cosigner/remote_cosigner.go (4)
1-1: The package name has been changed from "signer" to "cosigner". Confirm that this change is consistent throughout the codebase and that all references to this package have been updated.
24-24: The
clientfield in theRemoteCosignerstruct has been renamed toClient. Ensure that all references to this field have been updated to the new name.28-35: A new exported method
InitRemoteCosignerhas been added. Verify that this method is used correctly and that it initializes theRemoteCosignerstruct as expected.41-57: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [38-45]
The
NewRemoteCosignerfunction has been updated to useInitRemoteCosignerfor initialization. Confirm that this change does not introduce any regressions and that theRemoteCosigneris still initialized correctly.pkg/cosigner/nodesecurity/cosigner_security_ecies_test.go (3)
1-1: The package has been renamed to
nodesecurity_test. Confirm that this change is consistent with Go's naming conventions for test packages and that it does not affect the ability to test thenodesecuritypackage.30-38: The
CosignerSecuritytype has been replaced withnodesecurity.CosignerSecurityECIES, and thetestCosignerSecurityfunction has been split intotestCosignerSecurityRSAandtestCosignerSecurityECIES. Ensure that these changes are reflected in the tests and that the tests are still valid and pass.55-58: The
TestCosignerECIESfunction has been updated to use the newnodesecuritytypes. Verify that the test logic is correct and that the test cases cover the expected functionality.pkg/tss/types.go (3)
23-29: Introduced a new type
PersistentEd25519Keywith fields for public key, private shard, and index. Ensure that this type is used correctly and that the fields are accessed and modified appropriately.132-139: Added a generic function
WriteToFileto write keys to files. Verify that this function is implemented correctly, that it handles errors appropriately, and that it is used in places where key writing is required.116-125: The
ReadCometBFTPrivValidatorFilefunction has been added to read aprivval.FilePVKeyfrom a file. Confirm that this function correctly reads and unmarshals the key file, and that error handling is appropriate.signer/cosigner_grpc_server.go (3)
18-19: The
CosignerGRPCServerstruct has been renamed toNodeGRPCServer. Confirm that this renaming is consistent throughout the codebase and that all method receivers and references have been updated accordingly.55-63: The
SetNoncesAndSignmethod has been updated to access theMyCosignerfield ofthresholdValidatorinstead of directly accessingcosigner. Ensure that this change correctly reflects the intended design and that theMyCosignerfield is properly initialized and used.119-131: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [110-128]
The
TransferLeadershipmethod now includes logging comments. Verify that the logging is appropriate and that it provides useful information for debugging and monitoring the transfer of leadership.pkg/tss/threshold-ed25519_signer_soft.go (7)
1-1: The package has been correctly renamed to
tssto reflect its functionality.20-31: The new function
CreateEd25519ThresholdSignShardscorrectly creates shards for Ed25519 keys. Ensure that theIDfield starts from 1 as per the logic.34-39: The
IDfield inThresholdSignerSofthas been changed toid, making it unexported. Confirm that this change does not affect other parts of the codebase that may rely on this field being exported.42-65: The
NewThresholdEd25519SignerSoftfunction has been updated to use the new*config.RuntimeConfig. Ensure that all fields are correctly accessed and that theidfield is properly checked against the providedidargument.68-70: The
GetPubKeymethod has been correctly renamed to follow Go naming conventions for getter methods.109-116: The
GenerateNoncesmethod inNonceGeneratorcorrectly generates nonces using cryptographic randomness. Ensure that the error handling is adequate and that the generated nonces meet the security requirements.134-137: The
CombineSignaturesmethod has been added to combine partial signatures. Verify that the combination logic is secure and correctly implemented, especially the handling of ephemeral public keys.cmd/horcrux/cmd/leader_election.go (2)
8-8: The import path has been updated to use the
nodesecuritypackage, which is consistent with the reorganization of the codebase.120-130: The functions
LoadCosignerRSAKeyandLoadCosignerECIESKeyhave been moved to thenodesecuritypackage. Confirm that all references to these functions have been updated throughout the codebase.cmd/horcrux/cmd/config.go (6)
8-8: The import path has been updated to use the
cconfigpackage, aligning with the refactor.51-54: The
initCmdfunction now uses thecconfig.ChainNodesFromFlagfunction for configuration. Ensure that the configuration is correctly initialized and that error handling is adequate.70-90: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [63-90]
The
initCmdfunction creates acconfig.Configobject with fields initialized from command-line flags. Verify that all fields are correctly assigned and that the configuration object is valid.
73-90: The handling of
SignModeThresholdin theinitCmdfunction appears to be correct. Ensure that the configuration for threshold mode is properly validated and that all necessary fields are set.105-109: The handling of
SignModeSinglein theinitCmdfunction appears to be correct. Ensure that the configuration for single sign mode is properly validated and that all necessary fields are set.137-141: The flag definitions in the
initCmdfunction have been updated to use thecconfigpackage types. Confirm that the flags are correctly defined and that their descriptions are accurate.pkg/cosigner/nodesecurity/cosigner_security_rsa.go (5)
1-1: The package has been correctly renamed to
nodesecurityto reflect its functionality.18-24: The
CosignerSecurityRSAstruct has been updated to implement thecosigner.ICosignerSecurityinterface. Confirm that the methods are correctly updated to use the new interface.26-29: The
CosignerRSAPubKeytype has been updated. Ensure that the type is correctly used in theEncryptAndSignmethod and that the method's logic is secure and correct.132-135: The
EncryptAndSignmethod now returns acosigner.CosignerNonce. Verify that the encryption and signing logic is secure and that the method correctly handles errors.198-201: The
DecryptAndVerifymethod now uses thecosigner.CosignerNoncetype. Confirm that the decryption and verification logic is secure and that the method correctly handles errors.pkg/cosigner/nodesecurity/cosigner_security_ecies.go (4)
1-1: The package has been correctly renamed to
nodesecurityto reflect its functionality.19-22: The
CosignerSecurityECIESstruct has been updated to implement thecosigner.ICosignerSecurityinterface. Confirm that the methods are correctly updated to use the new interface.140-144: The
EncryptAndSignmethod now returns acosigner.CosignerNonce. Verify that the encryption and signing logic is secure and that the method correctly handles errors.211-214: The
DecryptAndVerifymethod now uses thecosigner.CosignerNoncetype. Confirm that the decryption and verification logic is secure and that the method correctly handles errors.pkg/connector/sentry_signer_grpc_server.go (8)
1-1: The package has been correctly renamed to
connectorto reflect its functionality.20-30: The
SentrySignerGRPCServerstruct has been updated to use theIPrivValidatorinterface. Confirm that the interface is correctly implemented and that the server initialization logic is correct.36-44: The
NewSentrySignerGRPCServerfunction has been updated to accept anIPrivValidator. Verify that the validator is correctly used for server initialization.50-53: The
OnStartmethod has been updated to reflect the new server name and functionality. Ensure that the server starts correctly and listens on the specified address.62-64: The
OnStopmethod has been updated to reflect the new server name. Confirm that the server is gracefully stopped without issues.66-72: The
PubKeymethod has been updated to use themetricspackage for tracking requests. Confirm that the metrics are correctly incremented.86-93: The
Signmethod has been updated to use themetricspackage for tracking signing operations. Verify that the metrics are correctly incremented and that the signing logic is secure and correct.103-110: The
signAndTrackfunction has been updated to use themetricspackage and theIPrivValidatorinterface. Confirm that the signing and tracking logic is secure and correct, and that the metrics are correctly incremented.pkg/cosigner/local_cosigner_test.go (10)
1-1: The package name has been updated to
cosigner_test, which aligns with the new structure of the codebase.13-15: The imports have been updated to reflect the new package structure, ensuring that the test file references the correct packages.
47-47: The variable
securityis now a slice ofcosigner.ICosignerSecurityinterfaces, which suggests a move towards more abstracted and flexible code.60-64: The instantiation of
nodesecurity.NewCosignerSecurityRSAwithnodesecurity.CosignerRSAKeystruct reflects the updated package structure and usage of thenodesecuritypackage.83-83: Similar to the RSA security setup, the ECIES security setup also uses the
cosigner.ICosignerSecurityinterface, maintaining consistency in the approach to security abstractions.96-100: The instantiation of
nodesecurity.NewCosignerSecurityECIESwithnodesecurity.CosignerECIESKeystruct is consistent with the RSA setup and reflects the updated package structure.108-135: The
testLocalCosignerSignfunction has been updated to use thetypes.HRSTstruct, which is likely part of the refactoring to use more specific types for domain concepts.145-168: The
tss.Ed25519Keystruct is used to hold the public key and private shard information, aligning with the new package structure and refactoring efforts.203-222: The loop for signing with threshold cosigners has been updated to use the
cosigner.CosignerNonceandcosigner.CosignerSetNoncesAndSignRequesttypes, which is part of the refactoring to use more specific types and methods from thecosignerpackage.230-232: The
types.PartialSignaturestruct is used to hold the signature information, which is consistent with the refactoring to use more specific types for domain concepts.cmd/horcrux/cmd/shards.go (7)
23-25: The imports have been updated to reflect the new package structure, ensuring that the command file references the correct packages.
117-120: The function
tss.CreatePersistentEd25519ThresholdSignShardsFromFilereplaces the previoussigner.CreateEd25519ThresholdSignShardsFromFile, aligning with the new package structure and refactoring efforts.133-140: The
createCosignerDirectoryIfNecessaryandtss.WriteToFilefunctions are used to create directories and write shard files, which is consistent with the refactoring to use more specific functions from thetsspackage.175-178: The function
nodesecurity.CreateCosignerECIESShardsreplaces the previoussigner.CreateCosignerECIESShards, aligning with the new package structure and refactoring efforts.196-199: The function
nodesecurity.WriteCosignerECIESShardFilereplaces the previoussigner.WriteCosignerECIESShardFile, aligning with the new package structure and refactoring efforts.223-226: The function
nodesecurity.CreateCosignerRSAShardsreplaces the previoussigner.CreateCosignerRSAShards, aligning with the new package structure and refactoring efforts.244-247: The function
nodesecurity.WriteCosignerRSAShardFilereplaces the previoussigner.WriteCosignerRSAShardFile, aligning with the new package structure and refactoring efforts.cmd/horcrux/cmd/migrate.go (5)
11-14: The imports have been updated to reflect the new package structure, ensuring that the migration command file references the correct packages.
48-48: The field
ChainNodeshas been renamed toChainCosignerin thev2Configstruct, which likely reflects a change in the domain model to better represent the configuration.224-227: The
tss.Ed25519Keystruct is used to hold the public key and private shard information, aligning with the new package structure and refactoring efforts.240-243: The
nodesecurity.CosignerRSAKeystruct is used to hold the RSA key information, aligning with the new package structure and refactoring efforts.258-296: The migration logic has been updated to use the new
cconfig.ChainNodestype and associated constants for sign modes, which is part of the refactoring to use more specific types and constants from theconfigpackage.pkg/connector/sentry_signer.go (13)
1-5: The package name has been updated to
connector, and a comment block has been added to describe the purpose of the package, which aligns with the new structure of the codebase.29-39: The type
ReconnRemoteSentryhas been introduced, replacing the previousReconnRemoteSigner, and the associated methods have been updated accordingly. This change reflects the new naming convention and purpose of the type.64-72: The
OnStartandOnStopmethods forReconnRemoteSentryhave been updated, which is part of the refactoring to align with the new type name and functionality.74-77: The
establishConnectionmethod has been updated to use a context with a timeout, which is a good practice for network connections to prevent indefinite blocking.94-97: The
loopmethod forReconnRemoteSentryhas been updated, which is part of the refactoring to align with the new type name and functionality.108-118: The use of metrics from the
metricspackage instead of the previously used labels for tracking connection attempts is a good practice for monitoring and observability.166-169: The
handleRequestmethod has been updated to handle different types of requests, which is part of the refactoring to align with the new type name and functionality.182-185: The
handleSignVoteRequestmethod has been updated to handle vote signing requests, which is part of the refactoring to align with the new type name and functionality.202-205: The
handleSignProposalRequestmethod has been updated to handle proposal signing requests, which is part of the refactoring to align with the new type name and functionality.230-234: The
handlePubKeyRequestmethod has been updated to handle public key requests, and the use of metrics is a good practice for monitoring and observability.263-266: The
handlePingRequestmethod has been updated to handle ping requests, which is part of the refactoring to align with the new type name and functionality.281-294: The
StartRemoteSignersfunction has been updated to use theIPrivValidatorinterface and themetrics.StartMetricsfunction call, which is part of the refactoring to align with the new package structure and functionality.306-309: The
closeConnmethod has been updated to handle the closing of connections, which is part of the refactoring to align with the new type name and functionality.pkg/config/config.go (3)
1-1: The package name has been updated to
config, which aligns with the new structure of the codebase.29-35: The addition of default values for nonce cache intervals and timeouts is a good practice for providing sensible defaults and improving the configurability of the system.
110-111: The
RuntimeConfigstruct no longer contains methods forCosignerSecurityECIESandCosignerSecurityRSA, which suggests that these methods have been refactored out of the configuration struct.signer/raft_store.go (6)
1-6: The package description is clear and provides good context for the functionality of the
RaftStore.22-23: The import of the
cosignerpackage aligns with the refactoring efforts mentioned in the PR overview.39-39: Interface implementation assertion for
ILeaderis a good practice to ensureRaftStorecomplies with the interface.59-67: The renaming of the
cosignerfield tomycosignerand the change of its type to*cosigner.LocalCosignerare consistent with the refactoring goals. Ensure that all references to this field throughout the codebase are updated accordingly.92-92: The assignment of
mycosignertos.thresholdValidator.MyCosigneris consistent with the new field name in theRaftStorestruct.111-112: The removal of the
s.cosignerparameter from theNewNodeGRPCServerfunction call is consistent with the refactoring to use themycosignerfield.signer/cosigner_nonce_cache.go (12)
10-12: The addition of imports for
sync/atomic,horcrux/pkg/cosigner, andhorcrux/pkg/metricsis consistent with the changes in the codebase.42-42: The change of the
cachefield to a pointer type (*NonceCache) should be accompanied by proper initialization to avoid nil pointer dereferences.97-99: The
NonceCachePrunerinterface is clearly defined and provides a method for pruning nonces.122-144: The
PruneNoncesmethod has been updated to use atomic operations, which is a good practice for thread safety. Ensure that the logic for pruning nonces is correct and that the atomic operations are used consistently throughout the method.169-170: The change to accept
ICosignerandILeaderinterfaces in theNewCosignerNonceCachefunction is consistent with the refactoring to use interfaces for better abstraction.186-188: The
cachefield is properly initialized withnew(NonceCache), which is good practice to avoid nil pointer dereferences.225-227: The use of atomic operations in the
reconcilemethod is appropriate for thread safety. Ensure that the logic for calculating nonces per minute is correct.244-246: The use of a defer statement to store the last reconcile nonces using atomic operations is a good practice for ensuring the value is updated after the method's logic is executed.
296-297: The addition of metric tracking in the
LoadNmethod is consistent with the refactoring goals to incorporate performance monitoring.339-355: The
Startmethod's use of atomic operations and a ticker for periodic reconciliation is a good practice for ensuring thread safety and regular cache maintenance.389-392: The
GetNoncesmethod's use ofICosignerinterfaces and thecosignerpackage is consistent with the refactoring to use interfaces for better abstraction.406-408: The
ClearNoncesmethod's use of theICosignerinterface is consistent with the refactoring to use interfaces for better abstraction.pkg/metrics/metrics.go (5)
1-3: The renaming of the package to
metricsis consistent with the PR overview and reflects the purpose of the package.17-21: The addition of the
BeyondBlockErrortype is consistent with the need for specific error handling in the metrics package.23-27: The addition of the
SameBlockErrortype is consistent with the need for specific error handling in the metrics package.98-332: The addition of new Prometheus metrics is consistent with the refactoring goals to enhance metric tracking. Ensure that the metrics are registered correctly and follow Prometheus best practices.
342-342: The periodic update of Prometheus metrics in the
StartMetricsfunction is a good practice for ensuring metrics are up-to-date.test/validator_threshold.go (6)
- 15-17: The import paths have been updated to reflect the new package structure. Ensure that the new package paths are correct and that the new packages are being used appropriately in the code.
Verification successful
The search results confirm that the new package paths
github.com/strangelove-ventures/horcrux/pkg/config,github.com/strangelove-ventures/horcrux/pkg/cosigner/nodesecurity, andgithub.com/strangelove-ventures/horcrux/pkg/tssare being used in multiple files within the codebase. This indicates that the updated import paths in thevalidator_threshold.gofile are correct and align with the changes made across the codebase as part of the refactoring effort.* 35-35: The addition of the `totalSentries` parameter to the function `testChainSingleNodeAndHorcruxThreshold` should be reflected in all calls to this function. Verify that the new parameter is being passed correctly wherever this function is called.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the new package paths are correct and accessible. rg --type go "github.com/strangelove-ventures/horcrux/pkg/config" rg --type go "github.com/strangelove-ventures/horcrux/pkg/cosigner/nodesecurity" rg --type go "github.com/strangelove-ventures/horcrux/pkg/tss"Length of output: 3348
Verification successful
The executed script has successfully identified calls to the function
testChainSingleNodeAndHorcruxThresholdwithin thehorcrux_test.gofile. Each call includes six parameters, which aligns with the updated function signature that now includes thetotalSentriesparameter.Given this information, it can be concluded that the new parameter is being passed correctly wherever this function is called in the
horcrux_test.gofile.* 187-203: The function `convertValidatorToHorcrux` now uses types from the `config` and `nodesecurity` packages. Ensure that the new types are compatible with the existing code and that the function logic correctly handles the new types.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for calls to the function `testChainSingleNodeAndHorcruxThreshold` and verify the new parameter is included. ast-grep --lang go --pattern $'testChainSingleNodeAndHorcruxThreshold($_, $_, $_, $_, $_, $_)'Length of output: 851
Verification successful
The output from the shell script provides the full context of the
convertValidatorToHorcruxfunction, confirming that the function has been updated to use types from theconfigandnodesecuritypackages. The changes include the use ofconfig.CosignersConfig,config.CosignerConfig,config.ChainNodes,config.Config,config.SignModeThreshold, andconfig.ThresholdModeConfigfrom theconfigpackage, as well asnodesecurity.CreateCosignerECIESShardsfrom thenodesecuritypackage.The function appears to be correctly constructing configurations and other necessary structures using these new types. The loop starting at line 194 iterates over the total number of signers, setting up each cosigner's configuration. The
configandnodesecuritytypes are used to create shards, cosigner configurations, and the main configuration object for the threshold validator.Given the information provided, there are no apparent issues with the way the new types are being used in the
convertValidatorToHorcruxfunction. The logic seems to be consistent with the expected behavior described in the AI-generated summary.* 256-270: The function `getShardedPrivvalKey` now uses the `tss.Ed25519Key` type. Confirm that the `tss` package provides the expected functionality and that the `Ed25519Key` type is being used correctly within the function.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the new types from `config` and `nodesecurity` are used correctly in `convertValidatorToHorcrux`. ast-grep --lang go --pattern $'func convertValidatorToHorcrux($_, $_, $_, $_, $_, $_, $_, $_, $_) ($_,$_){$$$}'Length of output: 5202
Verification successful
To verify the correct usage of
tss.Ed25519Keyin thegetShardedPrivvalKeyfunction, I will check thetss.CreateEd25519ThresholdSignShardsfunction to confirm that it accepts anEd25519Keyand returns a slice ofEd25519Key.
To locate the
CreateEd25519ThresholdSignShardsfunction and verify its compatibility withtss.Ed25519Key, I will use a broader search pattern.
To determine the existence of the
CreateEd25519ThresholdSignShardsfunction within the codebase, I will perform a text-based search usingrg(ripgrep).
The
CreateEd25519ThresholdSignShardsfunction is defined to work withprivval.FilePVKeyand returns a slice ofEd25519Key, which confirms that thetss.Ed25519Keytype is being used correctly within thegetShardedPrivvalKeyfunction.* 277-278: The function `writeConfigAndKeysThreshold` now uses types from the `config` and `nodesecurity` packages. Verify that the new types are correctly integrated into the function and that the function's logic is still valid with these changes.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the `tss.Ed25519Key` type is being used correctly in `getShardedPrivvalKey`. ast-grep --lang go --pattern $'func getShardedPrivvalKey($_, $_, $_, $_) ($_,$_,$_){$$$}'Length of output: 784
Script:
#!/bin/bash # Verify the `tss.CreateEd25519ThresholdSignShards` function to ensure it works with `tss.Ed25519Key`. ast-grep --lang go --pattern $'func CreateEd25519ThresholdSignShards($_, $_, $_) ($_){$$$}'Length of output: 92
Script:
#!/bin/bash # Broaden the search for the `CreateEd25519ThresholdSignShards` function. ast-grep --lang go --pattern $'func CreateEd25519ThresholdSignShards($$$) {$$$}'Length of output: 81
Script:
#!/bin/bash # Search for the `CreateEd25519ThresholdSignShards` function using ripgrep. rg "CreateEd25519ThresholdSignShards"Length of output: 563
Verification successful
The output from the shell script provides the full context of the
writeConfigAndKeysThresholdfunction in thevalidator_threshold.gofile. The function takes parameters of types from theconfigandnodesecuritypackages and performs operations such as marshaling these types to YAML and JSON, respectively, and writing them to files.The parameters
config config.ConfigandeciesKey nodesecurity.CosignerECIESKeyare used to marshal the configuration and ECIES key to their respective formats and write them to files. The function also iterates overed25519Shardsto marshal and write each shard to a file.Based on the provided output, the new types from the
configandnodesecuritypackages are being used correctly within thewriteConfigAndKeysThresholdfunction. The logic for marshaling and writing the configuration and keys appears to be valid and there are no evident issues with the integration of the new types.* 338-341: The function `getSentriesForCosignerConnection` has a new comment and updated logic for handling the `sentriesPerSigner` parameter. Ensure that the logic correctly implements the intended behavior as described by the comment.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the new types from `config` and `nodesecurity` are used correctly in `writeConfigAndKeysThreshold`. ast-grep --lang go --pattern $'func writeConfigAndKeysThreshold($_, $_, $_, $_, $_) $_ {$$$}'Length of output: 2525
Verification successful
The logic within the
getSentriesForCosignerConnectionfunction in thetest/validator_threshold.gofile correctly implements the behavior described by the new comment. It handles the distribution of sentry cosigners to each node in the signer cluster according to thesentriesPerSignerparameter, including handling edge cases where the number of sentries is not evenly divisible by the number of signers.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the logic in `getSentriesForCosignerConnection` matches the new comment and correctly handles `sentriesPerSigner`. ast-grep --lang go --pattern $'func getSentriesForCosignerConnection($_, $_, $_) $_ {$$$}'Length of output: 3954
pkg/cosigner/local_cosigner.go (11)
- 1-1: The package name has been changed from
signertocosigner. Confirm that this change is consistent throughout the file and that no references to the old package name remain.Verification successful
The shell script results indicate that the package name
cosigneris used consistently in several files within thepkg/cosignerdirectory. Additionally, there are no files within thepkg/cosignerdirectory that match the old package namesigner. However, there are files outside of thepkg/cosignerdirectory that still contain the old package namesigner. This is expected as the script was designed to check for the absence of the old package name within Go files, and these occurrences may be in different packages or contexts where the old name is still valid.Based on the provided information, the change from
signertocosignerwithin thepkg/cosignerdirectory appears to be consistent, and there are no references to the old package name remaining in that directory.* 10-12: New imports have been added from the `horcrux` and `cosigner` packages. Verify that these imports are necessary and correctly used in the file.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the package name `cosigner` is used consistently and that there are no references to the old package name `signer`. rg --type go --files-with-matches "package cosigner" rg --type go --files-without-match "package signer"Length of output: 2063
Verification successful
The new imports in the
local_cosigner.gofile are indeed used within the file:
- The
configpackage is used for accessingRuntimeConfig,ThresholdModeConfig, andCosignerStateFile.- The
metricspackage is used for tracking time-related metrics such asSetPreviousLocalSignStart,SetPreviousLocalSignFinish, andSetPreviousLocalNonce.- The
tsspackage is used for generating nonces and creating a newThresholdEd25519SignerSoft.Based on this information, the imports are necessary and correctly used in the file.
* 36-38: The types of the `config`, `security`, and `chainState` fields have been changed. Ensure that the new types are correctly used in the `LocalCosigner` struct and that the rest of the code is compatible with these changes.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the new imports are necessary and used correctly in `local_cosigner.go`. rg --type go "github.com/strangelove-ventures/horcrux/pkg/config" local_cosigner.go rg --type go "github.com/strangelove-ventures/horcrux/pkg/metrics" local_cosigner.go rg --type go "github.com/strangelove-ventures/horcrux/pkg/tss" local_cosigner.goLength of output: 423
Script:
#!/bin/bash # Find the path of local_cosigner.go and verify the usage of new imports file_path=$(fd local_cosigner.go) if [[ ! -z "$file_path" ]]; then rg --type go "github.com/strangelove-ventures/horcrux/pkg/config" "$file_path" rg --type go "github.com/strangelove-ventures/horcrux/pkg/metrics" "$file_path" rg --type go "github.com/strangelove-ventures/horcrux/pkg/tss" "$file_path" else echo "File local_cosigner.go not found." fiLength of output: 559
Script:
#!/bin/bash # Check for references to the imported packages within local_cosigner.go file_path="pkg/cosigner/local_cosigner.go" # Check for config package usage echo "Searching for 'config' package usage:" rg --type go "config\." "$file_path" # Check for metrics package usage echo "Searching for 'metrics' package usage:" rg --type go "metrics\." "$file_path" # Check for tss package usage echo "Searching for 'tss' package usage:" rg --type go "tss\." "$file_path"Length of output: 1355
Verification successful
Let's try a more generalized ast-grep command to search for the
LocalCosignerstruct without specifying the fields to see if it exists in the codebase.
The ast-grep command successfully found the
LocalCosignerstruct in thelocal_cosigner.gofile, confirming the presence of theconfig,security, andchainStatefields with their new types as mentioned in the review comment:
configfield is of type*config.RuntimeConfigsecurityfield is of typeICosignerSecuritychainStatefield is of typesync.MapThese types match the changes described in the AI-generated summary and the review comment. Therefore, the new types are correctly used in the
LocalCosignerstruct.* 183-183: The call to `ccs.signer.GetPubKey()` has been updated. Verify that the `GetPubKey` method exists on the `ccs.signer` type and that it is being used correctly.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the new types are correctly used in the `LocalCosigner` struct. ast-grep --lang go --pattern $'type LocalCosigner struct { $$$ config $_; security $_; chainState $_; $$$ }'Length of output: 109
Script:
#!/bin/bash # Search for the LocalCosigner struct definition in the Go codebase ast-grep --lang go --pattern $'type LocalCosigner struct { $$$ }'Length of output: 856
Verification successful
To verify that the
GetPubKeymethod exists on theccs.signertype and that it is being used correctly, I will generate a script to check the definition of theccs.signertype to ensure that theGetPubKeymethod is indeed a part of its interface.
To correct the syntax error and verify the existence of the
GetPubKeymethod on theccs.signertype, I will generate a new script with a simplified pattern.
To verify the existence of the
GetPubKeymethod on theccs.signertype, I will now usergto search for the method definition within the Go files.
The output from the
rgcommand confirms that theGetPubKeymethod is defined for several types within the codebase, including*ThresholdSignerSoft,*RemoteCosigner,*ThresholdValidator,*SingleSignerValidator,*LocalCosigner,*FilePV, and within thePubKeyResponseandNoncemessage types in the protobuf definitions.Specifically, the
GetPubKeymethod is defined for the*LocalCosignertype in thepkg/cosigner/local_cosigner.gofile, which is likely the type referenced byccs.signerin the context of the original review comment.Given this information, it can be concluded that the
GetPubKeymethod does exist on theccs.signertype (assumingccs.signeris an instance of*LocalCosigneror one of the other types that have aGetPubKeymethod) and is being used correctly in the provided code snippet.* 211-211: The `VerifySignature` method now uses `ccs.signer.GetPubKey()`. Ensure that the `GetPubKey` method is correctly implemented and that the signature verification logic is correct.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the `GetPubKey` method exists on the `ccs.signer` type and is used correctly. ast-grep --lang go --pattern $'$_.$_.GetPubKey()'Length of output: 360
Script:
#!/bin/bash # Find the definition of the `ccs.signer` type to verify the existence of the `GetPubKey` method. ast-grep --lang go --pattern $'type $_ struct { $$$ signer $_ { $$$ GetPubKey() $$$ } $$$ }'Length of output: 616
Script:
#!/bin/bash # Simplified search for the type that has a method `GetPubKey`. ast-grep --lang go --pattern $'type $_ struct { $$$ GetPubKey() $$$ }'Length of output: 77
Script:
#!/bin/bash # Use ripgrep to search for the GetPubKey method definition in Go files. rg 'func \(\w+ \*?\w+\) GetPubKey\(' -t goLength of output: 835
Verification successful
Let's adjust the script to match the
VerifySignaturemethod as it is used in the provided code snippet, which has two parameters and a return type. We will also look for theGetPubKeymethod implementation to ensure it is correctly implemented.
The verification scripts have successfully identified the implementation of the
GetPubKeymethod in several files, includingpkg/tss/threshold-ed25519_signer_soft.go,signer/file.go, and within the protobuf generated filessigner/proto/remote_signer.pb.goandsigner/proto/cosigner.pb.go. Additionally, the usage of theGetPubKeymethod in theVerifySignaturemethod has been confirmed inpkg/cosigner/local_cosigner.go.Based on the output, it can be concluded that the
GetPubKeymethod is implemented and used within theVerifySignaturemethod as intended in the codebase.* 228-228: The `metrics.MetricsTimeKeeper.SetPreviousLocalSignStart` method is being called. Confirm that this method exists and is being used correctly to track the timing of local signing operations.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the `GetPubKey` method is correctly implemented and used in the `VerifySignature` method. ast-grep --lang go --pattern $'func ($_ $_) VerifySignature($_, $_, $_) $_ {$$$}'Length of output: 82
Script:
#!/bin/bash # Verify the implementation of the `GetPubKey` method. ast-grep --lang go --pattern $'func ($_ $_) GetPubKey() $_ {$$$}' # Verify the usage of `GetPubKey` in the `VerifySignature` method. ast-grep --lang go --pattern $'func ($_ $_) VerifySignature($_, $_) $_ {$$$}'Length of output: 2296
- 280-280: The
metrics.MetricsTimeKeeper.SetPreviousLocalSignFinishmethod is being called. Confirm that this method exists and is being used correctly to track the timing of local signing operations.Verification successful
The
SetPreviousLocalSignFinishmethod exists and is used correctly inlocal_cosigner.goat line 280, as verified by the script output.* 289-292: The `tss.NonceGenerator{}.GenerateNonces` method is being called. Verify that this method exists and is being used correctly to generate nonces.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the `SetPreviousLocalSignFinish` method exists and is used correctly. ast-grep --lang go --pattern $'metrics.MetricsTimeKeeper.SetPreviousLocalSignFinish($_)'Length of output: 192
- 319-321: The
tss.NewThresholdEd25519SignerSoftfunction is being called. Confirm that this function exists and is being used correctly to create a new signer.Verification successful
The shell script has confirmed that the
tss.NewThresholdEd25519SignerSoftfunction exists and is being used in thelocal_cosigner.gofile with three arguments. This matches the usage pattern in the provided code snippet from the PR, indicating that the function is indeed being used correctly to create a new signer.* 336-342: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [339-345]Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the `NewThresholdEd25519SignerSoft` function exists and is used correctly. ast-grep --lang go --pattern $'tss.NewThresholdEd25519SignerSoft($_, $_, $_)'Length of output: 212
The
config.RuntimeConfigandconfig.Configtypes are being used to configure theLocalCosigner. Ensure that these types are correctly defined and used within theLocalCosignerstruct.Verification successful
The extracted definition of the
LocalCosignerstruct frompkg/cosigner/local_cosigner.goconfirms that theconfigfield is indeed of type*config.RuntimeConfig. This aligns with the changes mentioned in the review comment and the AI-generated summary, verifying that theconfig.RuntimeConfigtype is correctly defined and used within theLocalCosignerstruct.* 353-363: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [352-356]Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the `config.RuntimeConfig` and `config.Config` types are correctly defined and used. ast-grep --lang go --pattern $'type LocalCosigner struct { $$$ config *config.RuntimeConfig; $$$ }'Length of output: 100
Script:
#!/bin/bash # Verify the type of the `config` field in the `LocalCosigner` struct. ast-grep --lang go --pattern $'type LocalCosigner struct { $$$ config $_; $$$ }'Length of output: 81
Script:
#!/bin/bash # Find the file where the `LocalCosigner` struct is defined. rg "type LocalCosigner struct" --files-with-matchesLength of output: 84
Script:
#!/bin/bash # Extract the definition of the `LocalCosigner` struct from the identified file. cat pkg/cosigner/local_cosigner.go | grep -A 10 "type LocalCosigner struct"Length of output: 433
The
nodesecurity.NewCosignerSecurityECIESfunction is being called. Confirm that this function exists and is being used correctly to create a new instance ofICosignerSecurity.signer/threshold_validator_test.go.txt (8)
- 1-1: The package name has been changed to
signer_test. Confirm that this change is consistent throughout the file and that no references to the old package name remain.Verification successful
The verification scripts have confirmed that the package name
signer_testis used consistently in several test files within thesignerdirectory. Additionally, there are no matches for the old package namesignerin any.gofiles, which suggests that the renaming has been applied correctly in the context of Go test files.However, the absence of the old package name in
.gofiles does not necessarily mean that it has been completely removed from the entire codebase, as the package could still be referenced in non-Go files or in Go files that do not declare the package (e.g., files that import the package). The script output lists many files that do not contain the string "package signer", but without context, we cannot determine if these files should have been affected by the renaming.Based on the information provided, the change to the package name
signer_testin the context of Go test files seems to have been applied correctly.* 13-17: New imports have been added from the `horcrux` and `cosigner` packages. Verify that these imports are necessary and correctly used in the file.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the package name `signer_test` is used consistently and that there are no references to the old package name `signer`. rg --type go --files-with-matches "package signer_test" rg --type go --files-without-match "package signer"Length of output: 1990
Verification successful
The executed script has successfully located the file
signer/threshold_validator_test.go.txtand confirmed the presence of the new imports within it. Each of the imports fromgithub.com/strangelove-ventures/horcruxand its sub-packages has been found in the file, indicating that they are indeed used inthreshold_validator_test.go.* 39-39: The function `testThresholdValidator` has been updated to accept an additional `configuration` parameter. Verify that the new parameter is being passed correctly wherever this function is called.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the new imports are necessary and used correctly in `threshold_validator_test.go.txt`. rg --type go "github.com/strangelove-ventures/horcrux/pkg/config" threshold_validator_test.go.txt rg --type go "github.com/strangelove-ventures/horcrux/pkg/cosigner" threshold_validator_test.go.txt rg --type go "github.com/strangelove-ventures/horcrux/pkg/cosigner/nodesecurity" threshold_validator_test.go.txt rg --type go "github.com/strangelove-ventures/horcrux/pkg/tss" threshold_validator_test.go.txt rg --type go "github.com/strangelove-ventures/horcrux/signer" threshold_validator_test.go.txtLength of output: 859
Script:
#!/bin/bash # Correct the file extension and verify that the new imports are necessary and used correctly in `threshold_validator_test.go`. rg --type go "github.com/strangelove-ventures/horcrux/pkg/config" threshold_validator_test.go rg --type go "github.com/strangelove-ventures/horcrux/pkg/cosigner" threshold_validator_test.go rg --type go "github.com/strangelove-ventures/horcrux/pkg/cosigner/nodesecurity" threshold_validator_test.go rg --type go "github.com/strangelove-ventures/horcrux/pkg/tss" threshold_validator_test.go rg --type go "github.com/strangelove-ventures/horcrux/signer" threshold_validator_test.goLength of output: 819
Script:
#!/bin/bash # Locate the `threshold_validator_test.go` file within the repository and verify the usage of the new imports. file_path=$(fd threshold_validator_test.go | head -n 1) if [[ ! -z "$file_path" ]]; then rg --type go "github.com/strangelove-ventures/horcrux/pkg/config" "$file_path" rg --type go "github.com/strangelove-ventures/horcrux/pkg/cosigner" "$file_path" rg --type go "github.com/strangelove-ventures/horcrux/pkg/cosigner/nodesecurity" "$file_path" rg --type go "github.com/strangelove-ventures/horcrux/pkg/tss" "$file_path" rg --type go "github.com/strangelove-ventures/horcrux/signer" "$file_path" else echo "File threshold_validator_test.go not found in the repository." fiLength of output: 1033
55-61: The function
loadKeyForLocalCosignerhas been updated to use thecosigner.LocalCosignertype and a newconfigparameter. Ensure that the new type and parameter are correctly used within the function.90-95: The
signer.NewThresholdValidatorfunction is being called with a newconfigurationparameter. Verify that this parameter is being used correctly within the function and that the function's logic is still valid with this change.Verification successful
The search for the definition of the
NewThresholdValidatorfunction has yielded two results, indicating that the function is defined in bothsigner/threshold_validator.goandcmd/horcrux/cmd/threshold.go. To verify the correct usage of theconfigurationparameter, we need to inspect the implementation withinsigner/threshold_validator.gosince that is likely where the logic for theThresholdValidatoris defined.I will generate a script to extract the function definition from
signer/threshold_validator.goto ensure that theconfigurationparameter is being used correctly.
The function definition for
NewThresholdValidatorinsigner/threshold_validator.gohas been successfully retrieved. Theconfigurationparameter is indeed the second parameter of the function, and it is of type*config.RuntimeConfig. This confirms that theconfigurationparameter is expected by the function and is used in its signature.Given this information, the
configurationparameter is being used correctly within theNewThresholdValidatorfunction as per the changes in the pull request. The function's logic is expected to be valid with this change, assuming that the rest of the function implementation correctly utilizes theconfigurationparameter.* 177-182: The `signer.NewThresholdValidator` function is being called again with the new `configuration` parameter. Confirm that this parameter is being used correctly and that the function's logic is still valid with this change.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the `NewThresholdValidator` function uses the new `configuration` parameter correctly. ast-grep --lang go --pattern $'signer.NewThresholdValidator($_, $_, $_, $_, $_, $_, $_, $_)'Length of output: 626
Script:
#!/bin/bash # View the implementation of the `NewThresholdValidator` function to verify the usage of the `configuration` parameter. ast-grep --lang go --pattern $'func (NewThresholdValidator)($_, $_, $_, $_, $_, $_, $_, $_) {$$$$}'Length of output: 100
Script:
#!/bin/bash # Search for the definition of the `NewThresholdValidator` function to verify the usage of the `configuration` parameter. rg "func NewThresholdValidator"Length of output: 148
Script:
#!/bin/bash # Extract the function definition of `NewThresholdValidator` from `signer/threshold_validator.go`. rg -A 10 "func NewThresholdValidator" signer/threshold_validator.goLength of output: 389
- 338-345: The
config.RuntimeConfigandconfig.Configtypes are being used to configure theLocalCosigner. Ensure that these types are correctly defined and used within theLocalCosignerstruct.Verification successful
The verification script has confirmed the existence of the
LocalCosignerstruct within thepkg/cosigner/local_cosigner.gofile. It includes a field namedconfigwhich is a pointer toconfig.RuntimeConfig. This aligns with the usage ofconfig.RuntimeConfigin the provided code snippet, indicating that the types are indeed correctly defined and used within theLocalCosignerstruct.* 352-356: The `nodesecurity.NewCosignerSecurityECIES` function is being called. Confirm that this function exists and is being used correctly to create a new instance of `ICosignerSecurity`.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the `config.RuntimeConfig` and `config.Config` types are correctly defined and used. ast-grep --lang go --pattern $'type LocalCosigner struct { $$$ config *config.RuntimeConfig; $$$ }'Length of output: 100
Script:
#!/bin/bash # Verify the existence and definition of the `LocalCosigner` struct. ast-grep --lang go --pattern $'type LocalCosigner struct { $$$ }'Length of output: 856
Verification successful
The
NewCosignerSecurityECIESfunction does exist in the codebase, as confirmed by the output from thergcommand. It is defined in the filepkg/cosigner/nodesecurity/cosigner_security_ecies.go. Therefore, the function is available for use and the code snippet in the pull request is using an existing function correctly to create a new instance ofICosignerSecurity.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the `NewCosignerSecurityECIES` function exists and is used correctly. ast-grep --lang go --pattern $'nodesecurity.NewCosignerSecurityECIES($_)'Length of output: 74
Script:
#!/bin/bash # Search for the definition of NewCosignerSecurityECIES function across all Go files. rg "func NewCosignerSecurityECIES" --type goLength of output: 176
pkg/types/sign_state.go (9)
33-35: The mutex
muand condition variablecondhave been marked as private to avoid marshalling issues. This is a good practice to prevent unintended serialization of synchronization primitives, which can lead to state corruption and concurrency bugs.54-62: The methods
CondUnlockandCondBroadcasthave been added to unlock the mutex and broadcast a signal to all waiting goroutines, respectively. These methods encapsulate the condition variable operations, which is a good encapsulation practice.107-115: The method
hrsretrieves the currentHRSfrom theSignState. It correctly acquires a read lock before accessing the state, which is necessary for thread safety.117-121: The method
hrsKeyLockedis similar tohrsbut does not acquire a lock, implying it should be called from a context where the lock is already held. This is a good practice to avoid redundant locking and should be used with caution to ensure the lock is indeed held when called.133-137: The
HRSKeymethod in theSignStateConsensusstruct returns theHRSassociated with the consensus state. This method is straightforward and correctly constructs theHRSfrom the struct's fields.323-326: The
CheckHRSmethod correctly checks for height regression and returns an appropriate error if detected. The method's logic appears to be sound and follows the expected behavior for regression checking.356-359: The
newSameHRSErrorfunction creates an error indicating that theHRSis the same as the current one. This is a specific error type that can be useful for debugging and error handling.363-374: The
GetErrorIfLessOrEqualmethod checks if the providedHRSis less than or equal to the currentHRSand returns an error if so. The method name and implementation are clear and concise.387-397: The
FreshCachemethod creates a newSignStatewith a fresh cache, including the most recent sign state. It correctly initializes a new cache map and copies over the relevant fields from the current state. This method is useful for resetting the state while retaining the current signing information.test/horcrux_test.go (8)
9-17: The test file now imports the
nodesecuritypackage, which is likely related to the new security features introduced in the refactor. The import changes reflect the reorganization of the codebase.30-60: The test functions have been updated to reflect the new terminology and structure of the codebase. The comments have been updated to match the new naming conventions, which is important for clarity and maintainability.
143-146: The test function
TestDownedSigners2of3has been added to test the behavior of the system when two signers are down in a 2/3 threshold setup. This is a critical test case for ensuring the robustness of the signing mechanism in failure scenarios.186-188: The test function
TestDownedSigners3of5is similar toTestDownedSigners2of3but for a 3/5 threshold setup. It's good to see tests covering different configurations, which helps ensure the system's reliability across various setups.456-457: The
cosignerChainConfigstruct has been updated to use thetss.Ed25519Keytype for theshardsfield, reflecting the changes in the codebase's structure and naming conventions.470-473: The
configureAndStartSidecarsfunction now takes an additional parametereciesShardsof type[]nodesecurity.CosignerECIESKey. This change likely relates to the new security features and is important for setting up the test environment correctly.482-487: The
cosignersConfigis being constructed with the incorrect fieldP2PAddr. The format string suggests it should be a TCP address, but it uses a variablesignerPortwhich is not defined in the provided context. This could be a mistake or an oversight.Verification successful
The search across the codebase for
signerPorthas yielded several results. It is defined in thetest/validator.gofile with the value"2222". This definition is used in multiple places within the test code, including the construction of Docker container configurations and obtaining host ports.Given this information, the usage of
signerPortin thecosignersConfigwithintest/horcrux_test.gois correct, assuming that thetest/validator.gofile is part of the same test suite and is included or executed in a context wheresignerPortis defined beforecosignersConfigis constructed.* 522-527: The `config` struct has been updated to use the `config.SignModeThreshold` and `config.ThresholdModeConfig`. This change aligns with the refactor and indicates a shift to a threshold-based signing mode, which is a significant change in functionality.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the signerPort is defined and correctly used in the cosignersConfig. # This script is a placeholder for the actual logic that needs to be verified. echo "Verify the definition and usage of signerPort in cosignersConfig."Length of output: 140
Script:
#!/bin/bash # Search for the definition of signerPort within the test/horcrux_test.go file rg "signerPort" test/horcrux_test.goLength of output: 111
Script:
#!/bin/bash # Search for the definition of signerPort across the entire codebase rg "signerPort" -t goLength of output: 523
signer/threshold_validator.go (36)
9-9: The addition of the
stringspackage suggests new string manipulation operations have been introduced. Ensure that these operations are necessary and correctly implemented.29-29: The
ThresholdValidatornow implements theconnector.IPrivValidatorinterface. Verify that all required methods are implemented and that the implementation adheres to the interface's contract.32-44: The
nodecacheconfigstype andnodecacheconfigfunction have been added. Ensure that the configuration values are correctly used throughout the code and that the naming convention is consistent with the rest of the codebase.49-49: The
configfield inThresholdValidatorhas been changed to a pointer toconfig.RuntimeConfig. Ensure that all usages of this field are updated to handle the pointer correctly and check for potentialnildereferences.56-56: The
chainSignStatefield has been changed from a specific type to async.Map. This change implies concurrent access. Verify that all operations onchainSignStateare safe and correctly handle the concurrent nature ofsync.Map.79-90: New error type
StillWaitingForBlockErrorhas been added. Ensure that it is used consistently and that error handling logic is correctly implemented wherever this error type is used.92-103: New error type
SameBlockErrorhas been added. Similar to the previous comment, ensure that it is used consistently and that error handling logic is correctly implemented wherever this error type is used.116-133: New error type
BeyondBlockErrorhas been added. Similar to the previous comments, ensure that it is used consistently and that error handling logic is correctly implemented wherever this error type is used.138-164: The
NewThresholdValidatorfunction has been refactored. Ensure that all parameters are correctly used within the function and that the function's behavior is consistent with its intended purpose.171-176: The
ThresholdValidatorstruct initialization has been updated. Verify that all fields are initialized correctly and that the new fields are properly integrated into the struct's methods.188-188: The
StartNoncePrunermethod is being called onMyCosigner. Ensure that this method exists and is correctly implemented in theLocalCosignertype.206-213: The
mustLoadChainStatemethod has been updated to handle the newsync.Maptype forchainSignState. Ensure that the type assertion is correct and that the error handling is appropriate.229-232: The
SaveLastSignedStateInitiatedmethod has been updated. Verify that the new logic correctly handles the saving of the initiated sign state and that error handling is appropriate.243-243: The
newBeyondBlockErrormethod is being used to create an error. Ensure that this method is correctly implemented and that the error is handled appropriately in the calling context.277-280: The
CondWaitWithTimeoutmethod is being used. Verify that the condition variable is used correctly and that the timeout logic is appropriate for the context in which it is used.320-323: The
notifyBlockSignErrormethod is being introduced. Ensure that this method is correctly implemented and that it is called in appropriate error scenarios.345-345: The
WaitForSignStatesToFlushToDiskmethod is being called onMyCosigner. Verify that this method exists and is correctly implemented in theLocalCosignertype.351-354: The
GetPubKeymethod has been updated. Ensure that the new logic correctly retrieves the public key and that error handling is appropriate.359-361: The
LoadSignStateIfNecessarymethod has been updated. Verify that the new logic correctly handles the loading of the sign state and that error handling is appropriate.368-379: The
LoadSignStateIfNecessarymethod has been updated with new logic for initializinglastInitiatedSignState. Ensure that this logic is correct and that the sign state is being handled appropriately.388-395: The
getExistingBlockSignaturemethod has been updated. Verify that the new logic correctly retrieves existing block signatures and that error handling is appropriate.415-419: The
compareBlockSignatureAgainstSSCmethod has been updated. Ensure that the comparison logic is correct and that error handling is appropriate for the context in which it is used.438-447: The
compareBlockSignatureAgainstHRSfunction has been updated. Verify that the comparison logic is correct and that error handling is appropriate for the context in which it is used.459-466: The
getNoncesFallbackmethod has been added. Ensure that this method is correctly implemented and that it is called in appropriate scenarios where a fallback is necessary.472-476: The
waitForPeerNoncesmethod has been updated. Verify that the new logic correctly waits for nonces from peers and that error handling is appropriate.566-567: The
proxyIfNecessarymethod has been updated. Verify that the new logic correctly handles proxying requests to the leader and that error handling is appropriate.587-590: The
proxyIfNecessarymethod has been updated with a call toSignon aRemoteCosigner. Ensure that this call is correctly implemented and that error handling is appropriate.596-599: The
proxyIfNecessarymethod has been updated with new error handling logic. Verify that this logic correctly handles errors returned from theSignmethod call.666-672: The
Signmethod has been updated with new error handling logic. Verify that this logic correctly handles errors when getting nonces and that the fallback mechanism is appropriate.717-722: The
Signmethod has been updated with a call toSetNoncesAndSignon aRemoteCosigner. Ensure that this call is correctly implemented and that error handling is appropriate.730-732: The
Signmethod has been updated with logic to clear nonces from the nonce cache. Verify that this logic is correct and that the nonce cache is being handled appropriately.739-740: The
Signmethod has been updated with logic to mark a cosigner as unhealthy. Verify that this logic is correct and that the health status of cosigners is being handled appropriately.797-801: The
Signmethod has been updated with logic to combine signatures. Verify that this logic is correct and that error handling is appropriate.804-809: The
Signmethod has been updated with logic to verify the combined signature. Verify that this logic is correct and that error handling is appropriate.831-833: The
Signmethod has been updated with logic to handle errors when saving the last sign state. Verify that this logic is correct and that error handling is appropriate.846-846: The
Signmethod has been updated with a call tometrics.TimedSignBlockLag.Observe. Verify that this metric is being used correctly and that it accurately reflects the sign block lag.
signer/threshold_validator.go
Outdated
| // MPC *MPC // This is our multi party computation/communucatibn | ||
| // our own cosigner | ||
| myCosigner *LocalCosigner | ||
| MyCosigner *cosigner.LocalCosigner // TODO Should be an interface as well. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The MyCosigner field comment suggests it should be an interface. If this is a TODO item, ensure there is a tracking issue or further documentation to address this in the future.
| hrst := block.ToHRST() | ||
| /* | ||
| types.HRST{ | ||
| Height: height, | ||
| Round: round, | ||
| Step: step, | ||
| Timestamp: stamp.UnixNano(), | ||
| } | ||
| */ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The Sign method has been updated with commented-out code. Ensure that this commented-out code is either removed or implemented, and verify that the logic surrounding it is correct.
| /* | ||
| const ( | ||
| defaultGetNoncesInterval = 3 * time.Second | ||
| defaultGetNoncesTimeout = 4 * time.Second | ||
| defaultNonceExpiration = 10 * time.Second // half of the local cosigner cache expiration | ||
| ) | ||
| ) | ||
| */ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The const block has been commented out. If these constants are no longer needed, they should be removed to avoid dead code.
- /*
- const (
- defaultGetNoncesInterval = 3 * time.Second
- defaultGetNoncesTimeout = 4 * time.Second
- defaultNonceExpiration = 10 * time.Second // half of the local cosigner cache expiration
- )
- */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.
| /* | |
| const ( | |
| defaultGetNoncesInterval = 3 * time.Second | |
| defaultGetNoncesTimeout = 4 * time.Second | |
| defaultNonceExpiration = 10 * time.Second // half of the local cosigner cache expiration | |
| ) | |
| ) | |
| */ |
| // GetCache is a get wrapper for [SignState.cache] | ||
| func (signState *SignState) GetCache(hrs HRS) (SignStateConsensus, bool) { | ||
| ssc, err := signState.cache[hrs] | ||
| return ssc, err | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The GetCache method has been added to retrieve SignStateConsensus from the cache map. The method should return a boolean indicating the presence of the key in the map, but it seems to be returning an error instead. This is likely a mistake since map access in Go returns a second boolean value, not an error.
- ssc, err := signState.cache[hrs]
- return ssc, err
+ ssc, ok := signState.cache[hrs]
+ return ssc, okCommittable 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.
| // GetCache is a get wrapper for [SignState.cache] | |
| func (signState *SignState) GetCache(hrs HRS) (SignStateConsensus, bool) { | |
| ssc, err := signState.cache[hrs] | |
| return ssc, err | |
| } | |
| // GetCache is a get wrapper for [SignState.cache] | |
| func (signState *SignState) GetCache(hrs HRS) (SignStateConsensus, bool) { | |
| ssc, ok := signState.cache[hrs] | |
| return ssc, ok | |
| } |
| func (signState *SignState) Unlock() { | ||
| signState.mu.Unlock() | ||
| } | ||
| func (signState *SignState) ExistingSignatureOrErrorIfRegression(hrst HRSTKey, signBytes []byte) ([]byte, error) { | ||
| func (signState *SignState) ExistingSignatureOrErrorIfRegression(hrst HRST, signBytes []byte) ([]byte, error) { | ||
| return signState.existingSignatureOrErrorIfRegression(hrst, signBytes) | ||
| } | ||
| func (signState *SignState) existingSignatureOrErrorIfRegression(hrst HRSTKey, signBytes []byte) ([]byte, error) { | ||
| func (signState *SignState) existingSignatureOrErrorIfRegression(hrst HRST, signBytes []byte) ([]byte, error) { | ||
| signState.mu.RLock() | ||
| defer signState.mu.RUnlock() | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [78-105]
The method ExistingSignatureOrErrorIfRegression checks for regression in the SignState and returns an existing signature if the sign bytes only differ by timestamp. The logic seems correct, but the method name could be more descriptive of its functionality, such as GetExistingSignatureIfValid.
| func (signState *SignState) GetFromCache(hrs HRS) (HRS, *SignStateConsensus) { | ||
| signState.mu.RLock() | ||
| defer signState.mu.RUnlock() | ||
| latestBlock := signState.hrsKeyLocked() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 NOTE
Codebase verification is a beta feature.
The output from the rg command provides several insights into how the cache field is accessed and modified within the SignState struct:
- The
GetCachemethod retrieves aSignStateConsensusfrom thecacheusing anHRSkey. - The
SetCachemethod updates thecachewith a newSignStateConsensusfor a givenHRS. - The
GetFromCachemethod retrieves thelatestBlockusing thehrsKeyLockedmethod and then checks if there is aSignStateConsensusfor the givenHRSin thecache. - The
cacheAndMarshalmethod includes logic to delete old entries from thecachebased on theHeightof a newSignStateConsensusand the constantblocksTocache.
From the last point, we can infer that the cache is maintained with a certain number of most recent blocks determined by blocksTocache. However, the GetFromCache method does not iterate over the cache to find the most recent block; it simply checks if there is an entry for the provided HRS.
Given this information, the review comment is valid in that the GetFromCache method does not ensure that the latestBlock is the most recent one from the cache. It only retrieves the SignStateConsensus for the current HRS of the SignState, which may not be the most recent one if the cache contains newer entries.
The method would need to be modified to iterate over the cache and find the entry with the highest Height (and possibly Round and Step depending on the definition of "most recent") to ensure that the latestBlock is indeed the most recent block from the cache.
- The
GetFromCachemethod inpkg/types/sign_state.godoes not iterate over thecacheto ensure that thelatestBlockis the most recent one. It only retrieves the entry for the currentHRSof theSignState.
Analysis chain
The GetFromCache method retrieves the latest signed block and the corresponding SignStateConsensus from the cache. The method should ensure that the latestBlock is the most recent one, which is not clear from the current implementation. It might be necessary to iterate over the cache to find the latest block.
The output from the rg command provides us with the context around the cache field within the SignState struct. It confirms that cache is a map with HRS as the key and SignStateConsensus as the value. However, this output does not give us information about how the cache is accessed or iterated to determine the most recent block.
To address the review comment, we need to understand how the cache is being used to ensure that the latestBlock retrieved by the GetFromCache method is indeed the most recent one. Since the rg command did not provide methods interacting with the cache, we should now search for methods that modify or access the cache field to understand how the latest block is determined.
Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Verify that the latestBlock is indeed the most recent block from the cache.
# This script is a placeholder for the actual logic that needs to be verified.
echo "Verify the logic to ensure latestBlock is the most recent block."
Length of output: 138
Script:
#!/bin/bash
# Search for the implementation of the method `hrsKeyLocked` within the codebase.
ast-grep --lang go --pattern $'func ($_ *SignState) hrsKeyLocked() HRS {
$$$
}'
Length of output: 440
Script:
#!/bin/bash
# Search for the cache structure and methods that interact with the cache.
ast-grep --lang go --pattern $'type ($_ *SignState) {
$$$
cache map[HRS]SignStateConsensus
$$$
}'
Length of output: 449
Script:
#!/bin/bash
# Correct the pattern and search for the SignState type definition with the cache field.
ast-grep --lang go --pattern $'type SignState struct {
$$$
cache map[HRS]SignStateConsensus
$$$
}'
Length of output: 105
Script:
#!/bin/bash
# Use ripgrep to search for the cache field within the SignState struct definition
# and any methods that interact with the cache.
rg "cache map\[HRS\]SignStateConsensus" -A 3 -B 3
Length of output: 496
Script:
#!/bin/bash
# Search for methods that modify or access the 'cache' field in the SignState struct.
rg "signState.cache" -A 5 -B 5
Length of output: 2956
| // WaitForSignStatesToFlushToDisk waits for all state file writes queued | ||
| // in SaveLastSignedState to complete before termination. | ||
| func (cosigner *LocalCosigner) waitForSignStatesToFlushToDisk() { | ||
| func (cosigner *LocalCosigner) WaitForSignStatesToFlushToDisk() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 NOTE
Codebase verification is a beta feature.
The search for the old method name waitForSignStatesToFlushToDisk has returned three occurrences in the file signer/threshold_validator.go. This indicates that the old method name is still being used and has not been completely replaced by the new method name WaitForSignStatesToFlushToDisk.
- The method is being called on an instance of
ThresholdValidator. - There is a comment describing the method.
- The method definition itself is present.
Given this information, it appears that not all references to the old method name have been updated to the new name.
- The old method name
waitForSignStatesToFlushToDiskis still present and being used insigner/threshold_validator.go.
Analysis chain
The method WaitForSignStatesToFlushToDisk has been renamed. Confirm that all references to the old method name have been updated to the new name.
Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Verify that all references to the old method name have been updated to `WaitForSignStatesToFlushToDisk`.
rg --type go "WaitForSignStatesToFlushToDisk"
Length of output: 410
Script:
#!/bin/bash
# Verify that the old method name `waitForSignStatesToFlushToDisk` is not being referenced anywhere.
rg --type go "waitForSignStatesToFlushToDisk"
Length of output: 324
| func testThresholdValidator(t *testing.T, threshold, total uint8, configuration *config.RuntimeConfig) { | ||
| cosigners, pubKey := getTestLocalCosigners(t, threshold, total) | ||
|
|
||
| thresholdCosigners := make([]Cosigner, 0, threshold-1) | ||
| thresholdCosigners := make([]signer.ICosigner, 0, threshold-1) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 NOTE
Codebase verification is a beta feature.
The search results confirm the presence of the configuration parameter in the testThresholdValidator function definition. However, the calls to testThresholdValidator show inconsistent usage of the configuration parameter. Only one call includes the configuration parameter, while the others do not. This inconsistency suggests that not all calls to the function have been updated to include the new parameter.
Based on the provided output, here are the findings:
- The
configurationparameter is present in the function definition oftestThresholdValidator. - The calls to
testThresholdValidatorare inconsistent; only one out of four calls includes the newconfigurationparameter.
Given these findings, it appears that there are issues with the updates to the calls of the testThresholdValidator function.
- The function
testThresholdValidatorhas been updated to include aconfigurationparameter, but not all calls to this function have been updated to pass this parameter. - Manual verification and correction are required to ensure that all calls to
testThresholdValidatorinclude the necessaryconfigurationparameter.
Analysis chain
The function testThresholdValidator now includes a configuration parameter. Confirm that this parameter is being used correctly within the function and that all calls to this function have been updated accordingly.
The rg command has successfully located the function testThresholdValidator within the file signer/threshold_validator_test.go.txt. The function signature includes the configuration *config.RuntimeConfig parameter as expected. To verify that this parameter is being used correctly within the function and that all calls to this function have been updated accordingly, we need to examine the body of the function testThresholdValidator and also search for all the calls to this function to ensure they include the new parameter.
Let's proceed with the verification by examining the usage of the configuration parameter within the function and checking for calls to this function.
Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Verify that the `configuration` parameter is being used correctly in `testThresholdValidator`.
ast-grep --lang go --pattern $'func testThresholdValidator($_, $_, $_, $_) {$$$}'
Length of output: 82
Script:
#!/bin/bash
# Search for the function `testThresholdValidator` to verify the usage of the `configuration` parameter.
ast-grep --lang go --pattern $'func testThresholdValidator($$$) {$$$}'
Length of output: 71
Script:
#!/bin/bash
# Use ripgrep to search for the function `testThresholdValidator` in the codebase.
rg "func testThresholdValidator"
Length of output: 299
Script:
#!/bin/bash
# Verify the usage of the `configuration` parameter within the `testThresholdValidator` function.
rg -A 10 "func testThresholdValidator" signer/threshold_validator_test.go.txt
# Search for calls to the `testThresholdValidator` function to ensure they include the new `configuration` parameter.
rg "testThresholdValidator\(" signer/threshold_validator_test.go.txt
Length of output: 1264
|
@coderabbitai review |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 12
Configuration used: CodeRabbit UI
Files ignored due to filter (1)
- signer/chain-1_priv_validator_state.json
Files selected for processing (26)
- cmd/horcrux/cmd/address.go (5 hunks)
- cmd/horcrux/cmd/config.go (6 hunks)
- cmd/horcrux/cmd/shards.go (7 hunks)
- pkg/cosigner/client.go (6 hunks)
- pkg/cosigner/cosigner.go (1 hunks)
- pkg/cosigner/icosigner.go (1 hunks)
- pkg/cosigner/icosigner_security.go (2 hunks)
- pkg/cosigner/local_cosigner_test.go (10 hunks)
- pkg/cosigner/nodesecurity/cosigner_security_ecies.go (4 hunks)
- pkg/cosigner/nodesecurity/cosigner_security_rsa.go (4 hunks)
- pkg/cosigner/server.go (21 hunks)
- pkg/tss/doc.go (1 hunks)
- pkg/tss/threshold-ed25519_signer_soft.go (5 hunks)
- pkg/tss/threshold_signer.go (1 hunks)
- pkg/tss/types.go (1 hunks)
- proto/strangelove/horcrux/cosigner.proto (2 hunks)
- proto/strangelove/horcrux/threshold_validator.proto (1 hunks)
- signer/cosigner_grpc_server.go (6 hunks)
- signer/cosigner_health.go (5 hunks)
- signer/cosigner_nonce_cache.go (12 hunks)
- signer/file.go (1 hunks)
- signer/icosigner.go (1 hunks)
- signer/raft_store.go (6 hunks)
- signer/single_signer_validator.go (3 hunks)
- signer/threshold_validator.go (31 hunks)
- signer/threshold_validator_test.go (12 hunks)
Additional comments: 160
pkg/cosigner/icosigner_security.go (1)
- 13-13: The return type of the
CreateNoncemethod has been changed fromCosignerNoncetoNonce. Verify that all implementations of this interface and the calling code are updated to handle the new return type correctly.proto/strangelove/horcrux/threshold_validator.proto (1)
- 6-12: The
TresholdValidatorservice has been defined with RPC methodsValidate,SignBlock,TransferLeadership, andGetLeader. Ensure that the corresponding server and client code are updated to handle these RPC methods correctly.signer/icosigner.go (1)
- 13-32: The
ICosignerinterface has been updated with new methods. Ensure that all implementations of this interface are updated to include these new methods and that they are correctly used throughout the codebase.pkg/tss/doc.go (1)
- 3-43: The package documentation for
tssprovides a clear overview of the package's purpose and usage. Ensure that the documentation is kept up-to-date with any changes to the package's API.proto/strangelove/horcrux/cosigner.proto (1)
- 6-13: The
Cosignerservice has been updated with new RPC methodsSignBlock,TransferLeadership, andGetLeader. Verify that the corresponding server and client code are updated to handle these RPC methods correctly.Verification successful
The server and client implementations for the
Cosignerservice have been updated to handle the new RPC methodsSignBlock,TransferLeadership, andGetLeaderas indicated by the presence of these methods in the server code (cosigner_grpc_server.go) and calls to these methods in the client code (client.go,leader_election.go,multi_test.go). The changes are consistent with the modifications made in theproto/strangelove/horcrux/cosigner.protofile.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for server implementations of the Cosigner service. rg --type go 'CosignerServer' # Search for client usages of the Cosigner service. rg --type go 'CosignerClient'Length of output: 4009
Script:
#!/bin/bash # Search for implementations of the new RPC methods in the server code. rg --type go 'func \([^)]+\) SignBlock\(' rg --type go 'func \([^)]+\) TransferLeadership\(' rg --type go 'func \([^)]+\) GetLeader\(' # Search for calls to the new RPC methods in the client code. rg --type go '\.SignBlock\(' rg --type go '\.TransferLeadership\(' rg --type go '\.GetLeader\('Length of output: 3256
pkg/tss/threshold_signer.go (1)
- 13-30: The function
LoadVaultKeyFromFilereads a key from a file and unmarshals it into anEd25519Keystruct. Ensure that error handling is correctly implemented and that the function is used properly throughout the codebase.Verification successful
The
LoadVaultKeyFromFilefunction is used in thethreshold-ed25519_signer_soft.gofile and thecmd/horcrux/cmd/address.gofile. This indicates that the function is indeed utilized within the codebase, and its impact is not limited to thethreshold_signer.gofile. The correct implementation of this function is crucial as it is part of the key management system and is used in multiple places.To ensure that the function is used properly and that error handling is correctly implemented, we should check the context in which
LoadVaultKeyFromFileis called in thethreshold-ed25519_signer_soft.goandcmd/horcrux/cmd/address.gofiles. This will help us understand if the function's return values are handled appropriately wherever it is invoked.
The usage context of
LoadVaultKeyFromFilein bothpkg/tss/threshold-ed25519_signer_soft.goandcmd/horcrux/cmd/address.goshows that the function's error return value is being handled correctly. In both instances, if an error occurs, it is not ignored; instead, the error is wrapped with additional context and returned, which is a good practice for error handling in Go.In
threshold-ed25519_signer_soft.go, ifLoadVaultKeyFromFilereturns an error, it is wrapped with the message "error reading Vault key" and the function returnsniland the error. Similarly, incmd/horcrux/cmd/address.go, an error fromLoadVaultKeyFromFileis wrapped with the message "error reading threshold key" along with thechainIDfor additional context, and the error is returned.This indicates that the function
LoadVaultKeyFromFileis correctly implemented with regard to error handling, and its usage in the codebase follows good practices by checking for errors and handling them appropriately.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for usages of the LoadVaultKeyFromFile function. rg --type go 'LoadVaultKeyFromFile'Length of output: 388
Script:
#!/bin/bash # Check the usage context of LoadVaultKeyFromFile in threshold-ed25519_signer_soft.go rg --type go --context 5 'LoadVaultKeyFromFile\(keyFile\)' pkg/tss/threshold-ed25519_signer_soft.go # Check the usage context of LoadVaultKeyFromFile in cmd/horcrux/cmd/address.go rg --type go --context 5 'LoadVaultKeyFromFile\(keyFile\)' cmd/horcrux/cmd/address.goLength of output: 761
signer/cosigner_health.go (2)
- 19-25: The
CosignerHealthstruct has been updated to use[]ICosignerandILeader. Verify that all instances of this struct are updated and that the methods are correctly handling the new types.Verification successful
The provided output confirms the following:
- The
NewCosignerHealthconstructor insigner/cosigner_health.gois correctly using the new types[]ICosignerandILeader.- The test function
TestCosignerHealthinsigner/cosigner_health_test.gois updated to reflect the new types, as it shows the initialization of aCosignerHealthinstance with a slice ofICosigner.However, the output does not include the contents of the
MarkUnhealthy,updateRTT, andGetFastestmethods fromsigner/cosigner_health.go. To complete the verification, we need to confirm that these methods are correctly handling the new types.Given the partial information, I will generate a new script to specifically extract the contents of the
MarkUnhealthy,updateRTT, andGetFastestmethods to ensure they are using the updated types.
Given the lack of output from the last script, it seems that the methods
MarkUnhealthy,updateRTT, andGetFastestfromsigner/cosigner_health.gocould not be retrieved using the previous approach. To ensure a thorough verification, I will attempt a different strategy to extract the method definitions.
The output from the script provides the necessary details to verify the methods in question:
- The
MarkUnhealthymethod correctly usesICosigneras the parameter type.- The
updateRTTmethod correctly uses*cosigner.RemoteCosigneras the parameter type.- The
GetFastestmethod correctly returns a slice of[]ICosigner.With this information, we can confirm that the
CosignerHealthstruct and associated methods are correctly handling the new types as per the changes described in the PR. All instances of this struct and the methods have been updated accordingly.* 64-68: The method `MarkUnhealthy` has been updated to accept an `ICosigner` interface. Ensure that all calls to this method are updated to pass the correct type.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for usages of the CosignerHealth struct. rg --type go 'CosignerHealth'Length of output: 1083
Script:
#!/bin/bash # Check the constructor and methods in cosigner_health.go cat signer/cosigner_health.go | grep -Pzo "(func NewCosignerHealth.*?\{.*?\n\}|func \(ch \*CosignerHealth\) MarkUnhealthy.*?\{.*?\n\}|func \(ch \*CosignerHealth\) updateRTT.*?\{.*?\n\}|func \(ch \*CosignerHealth\) GetFastest.*?\{.*?\n\})" # Check the field type in cosigner.go and threshold_validator.go cat pkg/cosigner/cosigner.go | grep 'cosignerHealth' cat signer/threshold_validator.go | grep 'cosignerHealth' # Check the test function in cosigner_health_test.go cat signer/cosigner_health_test.go | grep -Pzo "func TestCosignerHealth.*?\{.*?\n\}"Length of output: 719
Script:
#!/bin/bash # Extract the contents of the constructor and methods from cosigner_health.go cat signer/cosigner_health.go | grep -A 10 "func NewCosignerHealth" cat signer/cosigner_health.go | grep -A 10 "func (ch *CosignerHealth) MarkUnhealthy" cat signer/cosigner_health.go | grep -A 10 "func (ch *CosignerHealth) updateRTT" cat signer/cosigner_health.go | grep -A 10 "func (ch *CosignerHealth) GetFastest" # Extract the test function from cosigner_health_test.go cat signer/cosigner_health_test.go | grep -A 10 "func TestCosignerHealth"Length of output: 1108
Script:
#!/bin/bash # Extract the contents of the MarkUnhealthy, updateRTT, and GetFastest methods from cosigner_health.go cat signer/cosigner_health.go | grep -A 10 "func (ch *CosignerHealth) MarkUnhealthy" cat signer/cosigner_health.go | grep -A 10 "func (ch *CosignerHealth) updateRTT" cat signer/cosigner_health.go | grep -A 10 "func (ch *CosignerHealth) GetFastest"Length of output: 253
Script:
#!/bin/bash # Attempt to extract the method definitions using a different approach grep -E "func \(ch \*CosignerHealth\) MarkUnhealthy" signer/cosigner_health.go -A 10 grep -E "func \(ch \*CosignerHealth\) updateRTT" signer/cosigner_health.go -A 10 grep -E "func \(ch \*CosignerHealth\) GetFastest" signer/cosigner_health.go -A 10Length of output: 1206
Verification successful
The verification process has confirmed that the
MarkUnhealthymethod insigner/cosigner_health.gois being called with the correct typeICosignerinsigner/threshold_validator.go. ThecosignersForThisBlockslice, whichremote_cosigneris part of, is explicitly declared to hold elements of typeICosigner, ensuring type compatibility with the updated method signature.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for usages of the MarkUnhealthy method. rg --type go 'MarkUnhealthy'Length of output: 201
Script:
#!/bin/bash # Find the declaration of `remote_cosigner` in `threshold_validator.go` to verify its type. rg --type go -A 5 'remote_cosigner' signer/threshold_validator.goLength of output: 1765
Script:
#!/bin/bash # Search for the initialization or explicit type declaration of `remote_cosigner` to confirm it implements `ICosigner`. rg --type go -C 5 'remote_cosigner.*=' signer/threshold_validator.goLength of output: 1516
Script:
#!/bin/bash # Search for the definition of `cosignersForThisBlock` to determine the type of its elements. rg --type go -C 5 'cosignersForThisBlock' signer/threshold_validator.goLength of output: 1546
cmd/horcrux/cmd/address.go (1)
- 30-41: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [33-54]
The
addressCmdfunction has been updated to use thetss.PubKeytype and thecconfigpackage. Verify that the command is correctly handling the new types and package references.Verification successful
The shell script output indicates that the
addressCmdfunction is referenced incmd/horcrux/cmd/root.gowhere it is added as a command to the Cobra application, and it is defined incmd/horcrux/cmd/address.go. This confirms that theaddressCmdfunction is indeed part of the Cobra command setup and is used within the application.Given this information, the changes made to the
addressCmdfunction incmd/horcrux/cmd/address.go, as described in the original review comment, seem to be correctly handling the new types and package references. The function is updated to use thetss.PubKeytype and constants from thecconfigpackage, which aligns with the broader refactoring effort mentioned in the PR summary.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for usages of the addressCmd function. rg --type go 'addressCmd'Length of output: 141
signer/single_signer_validator.go (1)
- 87-95: The function
loadChainStateIfNecessaryhas been updated to use a renamed functionLoadPVFile. Verify that theLoadPVFilefunction exists and is correctly implemented.Verification successful
The
LoadPVFilefunction exists in thesigner/file.gofile and is correctly implemented to be used withinsingle_signer_validator.goas shown in the provided code snippet.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for the definition of the LoadPVFile function. rg --type go 'LoadPVFile'Length of output: 301
pkg/cosigner/cosigner.go (5)
3-10: The package comment has been updated to better describe the responsibilities of the
cosignerpackage. This is a good practice as it helps maintainers and new developers understand the purpose and functionality of the package.46-58: The
SignatureRequestandSignatureResponsetypes are well-defined and appear to be correctly structured for their intended use in network communication.68-76: The
toProtomethod correctly converts aNonceto its protobuf representation. Ensure that all fields are correctly mapped and that no data is lost in the conversion.122-130: The
Formethod inCosignerUUIDNoncesfilters nonces for a specific destination ID. Ensure that this method is tested thoroughly to confirm that it filters nonces correctly.134-143: The
ToProtomethod inCosignerUUIDNoncesMultipleconverts a slice ofCosignerUUIDNoncesto a slice of protobufUUIDNonce. Ensure that the conversion is accurate and that the UUID and nonces are correctly mapped.signer/cosigner_grpc_server.go (5)
16-24: The renaming of
CosignerGRPCServertoNodeGRPCServeris consistent throughout the file, and the constructor function has been updated accordingly.38-45: The
SignBlockmethod correctly uses thethresholdValidatorto sign a block. Ensure that thethresholdValidatoris properly initialized and that itsSignmethod is correctly implemented.51-63: The
SetNoncesAndSignmethod has been updated to use thethresholdValidatorand itsMyCosignerfield. Ensure that theSetNoncesAndSignmethod ofMyCosigneris correctly implemented and that the request is properly constructed.89-100: The
GetNoncesmethod has been updated to use thethresholdValidatorand itsMyCosignerfield. Ensure that theGetNoncesmethod ofMyCosigneris correctly implemented and that the UUIDs are properly handled.119-131: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [111-127]
The
TransferLeadershipmethod has been updated to use theraftStorefield. Ensure that theLeadershipTransferToServermethod of the Raft library is correctly used and that the logic for selecting the new leader is correct.pkg/cosigner/client.go (4)
14-24: The
RemoteCosignerstruct has been updated to export theClientfield, which is a necessary change for external packages to use theClientdirectly.26-34: The
InitRemoteCosignerfunction has been added as a placeholder for testing. Ensure that this function is only used for testing purposes and that it is correctly initializing theRemoteCosigner.132-150: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [124-139]
The
SetNoncesAndSignmethod's return type has been changed toSignatureResponse. Ensure that all callers of this method have been updated to handle the new return type correctly.
- 142-150: The comment indicates that the
Signmethod should move toThresholdValidator. This should be tracked in the project's issue tracker or roadmap to ensure it is not forgotten.pkg/tss/threshold-ed25519_signer_soft.go (7)
18-32: The
CreateEd25519ThresholdSignShardsfunction has been updated to use the newprivval.FilePVKeytype from thecometbftdependency. Ensure that the function correctly handles the new type and that the shards are correctly created.34-42: The
ted25519SignerSoftstruct has been renamed and updated to include anidfield. Ensure that theidfield is correctly used throughout the struct's methods.45-68: The
NewThresholdEd25519SignerSoftfunction has been updated to reflect the new struct name and logic. Ensure that the function correctly initializes theted25519SignerSoftinstance and that error handling is appropriate.71-80: The
GetPubKeyandSignmethods have been updated. Ensure that theGetPubKeymethod correctly returns the public key and that theSignmethod correctly signs the payload using the private key shard and nonces.84-90: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [87-110]
The
sumNoncesfunction has been extracted from theSignmethod. Ensure that the function correctly sums the nonces and that the resulting ephemeral public key and share are valid.
- 110-120: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [113-135]
The
NonceGeneratortype and itsGenerateNoncesmethod have been introduced. Ensure that the method correctly generates nonces and that the resulting nonces are valid for use in the MPC signature process.
- 138-142: The
CombineSignaturesmethod has been added toted25519SignerSoft. Ensure that the method correctly combines partial signatures into a full signature and that the resulting signature is valid.cmd/horcrux/cmd/config.go (7)
8-8: The import alias
cconfigfor the packagegithub.com/strangelove-ventures/horcrux/pkg/configis correctly defined and follows Go conventions for package aliasing when the package name is not the last element of the import path.51-54: The function
cconfig.ChainNodesFromFlagis correctly used to replace the previoussigner.ChainNodesFromFlag. Ensure that thecconfigpackage provides the same or compatible functionality.63-63: The variable
cfgis correctly declared with the new typecconfig.Config. This change is consistent with the package renaming and import path updates.73-73: The usage of
string(cconfig.SignModeThreshold)is correct and aligns with the new package structure. This change is part of updating constants to reflect the new package names.84-90: The initialization of
cconfig.Configfor threshold mode configuration is correct, with appropriate fields being set. This change is consistent with the package renaming and import path updates.105-109: The initialization of
cconfig.Configfor single signer configuration is correct, with appropriate fields being set. This change is consistent with the package renaming and import path updates.137-138: The flag
flagSignModeis correctly set to usestring(cconfig.SignModeThreshold)as the default value. This change is consistent with the package renaming and import path updates.pkg/tss/types.go (5)
72-76: The
Ed25519Keystruct is correctly defined for use with JSON marshaling. The field names are appropriate and the JSON tags are correctly applied.81-100: The
MarshalJSONmethod forEd25519Keyis implemented with a custom type alias to avoid recursion. The conversion to protobuf and marshaling logic appears correct. However, ensure that the protobuf definitions and thecometcryptoencodingpackage are compatible with this implementation.103-144: The
UnmarshalJSONmethod forEd25519Keyincludes a fallback mechanism for amino unmarshaling which is a good approach for backward compatibility. Ensure that the amino codec is correctly configured and that the fallback is tested.147-157: The
ReadCometBFTPrivValidatorFilefunction is correctly implemented to read and unmarshal a Comet privval.FilePVKey from a file. The error handling is appropriate, and the use ofcometjsonsuggests compatibility with CometBFT's JSON encoding.163-172: The generic
WriteToFilefunction is correctly implemented to marshal and write aVaultPrivateKeyto a file with secure permissions. The use of generics here is a modern Go feature that enhances code reusability.pkg/cosigner/nodesecurity/cosigner_security_rsa.go (5)
1-1: The package has been renamed to
nodesecurity, which is consistent with the PR's objective to reorganize and clarify the codebase.18-18: The implementation of the
ICosignerSecurityinterface from thecosignerpackage is correctly declared, ensuring thatCosignerSecurityRSAadheres to the expected interface.26-29: The
CosignerRSAPubKeystruct is correctly defined with anIDandPublicKey. This struct is used to map cosigner IDs to their RSA public keys, which is a common pattern in cryptographic applications.132-135: The
EncryptAndSignmethod's signature has been updated to return acosigner.Noncetype, which is consistent with the changes in thecosignerpackage. Ensure that theNoncetype is correctly defined in thecosignerpackage and that it contains all necessary fields.198-201: The
digestMsgvariable is of typecosigner.Nonce, which is consistent with the updated method signatures. Ensure that theNoncetype correctly represents the data structure needed for the encryption and signing process.pkg/cosigner/nodesecurity/cosigner_security_ecies.go (4)
1-1: The package has been renamed to
nodesecurity, which is consistent with the PR's objective to reorganize and clarify the codebase.19-19: The implementation of the
ICosignerSecurityinterface from thecosignerpackage is correctly declared, ensuring thatCosignerSecurityECIESadheres to the expected interface.140-144: The
EncryptAndSignmethod's signature has been updated to return acosigner.Noncetype, which is consistent with the changes in thecosignerpackage. Ensure that theNoncetype is correctly defined in thecosignerpackage and that it contains all necessary fields.211-214: The
digestMsgvariable is of typecosigner.Nonce, which is consistent with the updated method signatures. Ensure that theNoncetype correctly represents the data structure needed for the encryption and signing process.pkg/cosigner/local_cosigner_test.go (16)
1-1: Renaming the package to
cosigner_testis consistent with Go conventions for test packages.13-16: The updated imports reflect the new package structure and are correctly aliased.
47-47: The change from a concrete type to an interface
ICosignerSecurityincreases modularity and allows for easier testing.60-64: The use of
nodesecurity.NewCosignerSecurityRSAis correct and aligns with the new package structure.96-100: The use of
nodesecurity.NewCosignerSecurityECIESis correct and aligns with the new package structure.108-120: The replacement of old types with new ones from the
configpackage is correct and reflects the updated package structure.128-129: The change to use
cosigner.LocalCosignerandcosigner.Nonceis consistent with the new package structure.133-136: The replacement of
HRSTKeywithtypes.HRSTis correct and reflects the updated package structure.146-150: The replacement of
CosignerEd25519Keywithtss.Ed25519Keyis correct and reflects the updated package structure.152-154: The replacement of
CosignersConfigwithconfig.CosignerConfigis correct and reflects the updated package structure.159-163: The replacement of
RuntimeConfigwithconfig.RuntimeConfigis correct and reflects the updated package structure.164-169: The instantiation of
cosigner.NewLocalCosigneris correct and reflects the updated package structure.173-173: The use of
runtimeconfig.KeyFilePathCosigneris correct and reflects the updated package structure.176-176: The call to
cosigner.WaitForSignStatesToFlushToDiskis correct and reflects the updated package structure.219-223: The replacement of
SetNoncesAndSignwithlocal_cosigner.SetNoncesAndSignis correct and reflects the updated package structure.231-233: The use of
types.PartialSignatureis correct and reflects the updated package structure.cmd/horcrux/cmd/shards.go (7)
23-24: The introduction of new package imports for
nodesecurityandtssis correct and aligns with the updated package structure.117-120: The replacement of
signerpackage functions withtss.CreatePersistentEd25519ThresholdSignShardsFromFileis correct and aligns with the updated package structure.138-140: The use of
tss.WriteToFilefor writing the shard file is correct and aligns with the updated package structure.175-178: The replacement of
signerpackage functions withnodesecurity.CreateCosignerECIESShardsis correct and aligns with the updated package structure.196-198: The use of
nodesecurity.WriteCosignerECIESShardFilefor writing the ECIES shard file is correct and aligns with the updated package structure.223-226: The replacement of
signerpackage functions withnodesecurity.CreateCosignerRSAShardsis correct and aligns with the updated package structure.244-246: The use of
nodesecurity.WriteCosignerRSAShardFilefor writing the RSA shard file is correct and aligns with the updated package structure.signer/file.go (1)
- 156-156: The function
LoadFilePVhas been renamed toLoadPVFile, which is a minor change and does not affect functionality.signer/raft_store.go (5)
22-23: The addition of the
cosignerpackage import should be used within the file. Please ensure that the new package is utilized in the code changes.39-39: Please confirm that
RaftStoreimplements all methods required by theILeaderinterface.59-59: The
Cosignersfield inRaftStorehas been changed to a slice ofICosigner. Ensure that all usages of this field are updated to work with the interface type instead of a concrete type.67-67: The
mycosignerfield inRaftStorehas been updated to a pointer ofcosigner.LocalCosigner. Ensure that all usages of this field are correctly accessing the fields and methods ofLocalCosigner.114-114: The method
NewCosignerGRPCServerhas been replaced withNewNodeGRPCServer. Verify that this new method exists and is correctly implemented to handle the expected functionality.signer/cosigner_nonce_cache.go (13)
29-29: The
cosignersfield inCosignerNonceCachehas been changed to a slice ofICosigner. Ensure that all usages of this field are updated to work with the interface type instead of a concrete type.31-31: The
leaderfield inCosignerNonceCachehas been updated to theILeaderinterface type. Verify that all usages of this field are correctly accessing the methods ofILeader.33-33: The
lastReconcileNoncesfield has been replaced with an atomic variable. Ensure that all read and write operations to this field are now using atomic operations.42-42: The
cachefield inCosignerNonceCachehas been changed to a pointer type. Ensure that it is initialized before use to prevent null pointer dereferences.122-144: The
PruneNoncesmethod has been modified. Ensure that the new implementation correctly prunes nonces and that the method handles edge cases properly, such as when all nonces are expired.169-170: The
NewCosignerNonceCachefunction signature has been updated to accept slices ofICosignerand anILeader. Verify that the function correctly handles these interface types.186-189: The
CosignerNonceCachestruct is now initializing thecachefield as a pointer to a newNonceCache. Verify that this initialization is correct and that thecachefield is used safely throughout the code.225-230: The reconciliation process now uses atomic operations to load the
lastReconcileNonces. Verify that these operations are correctly synchronized across potential concurrent accesses.296-297: The
LoadNmethod now increments metrics on missed nonces. Ensure that the metrics are correctly updated and that the labels used for the metrics are properly defined.339-342: The
Startmethod now initializes thelastReconcileNoncesusing an atomic store. Verify that this initialization is correct and that the atomic variable is used safely throughout the code.359-359: The
GetNoncesmethod has been updated to use theICosignerinterface type. Ensure that the method correctly handles the interface type and that the logic for nonce retrieval is correct.383-389: The
GetNoncesmethod now triggers a reload when the nonce cache is empty. Verify that this behavior is correct and that the reload mechanism is properly implemented.406-409: The
ClearNoncesmethod has been updated to clear nonces for a specificICosigner. Verify that the method correctly identifies and removes nonces associated with the given cosigner.pkg/cosigner/server.go (20)
1-1: The package rename from
signertocosigneris consistent with the PR's refactoring objectives.10-12: Updates to import paths correctly reflect the new package names and structures.
36-38: Changes to type declarations in the
LocalCosignerstruct align with the updated package structure.49-50: The constructor function
NewLocalCosignerhas been correctly updated to use the new parameter types.68-68: The
ChainStatestruct has been updated to use theIThresholdSignerinterface, which is a good practice for abstraction.138-140: Renaming of the method
waitForSignStatesToFlushToDisktoWaitForSignStatesToFlushToDisklikely reflects a standardization of method names.162-165: The type assertion for
csto*ChainStateis a good practice to ensure the correct type is being operated on.183-183: The
GetPubKeymethod has been updated to useccs.signer.GetPubKey(), aligning with changes in theIThresholdSignerinterface.217-228: The
signmethod has been updated with new parameter types and the introduction of metric tracking, which is a positive change for performance monitoring.280-280: Continuation of metric tracking in the
signmethod is consistent with the earlier part of the method and is a good practice.319-320: Instantiation of
IThresholdSignerusingtss.NewThresholdEd25519SignerSoftaligns with the new interface-based approach.338-338: Introduction of metric tracking in the
GetNoncesmethod is a good practice for performance monitoring.355-358: Parallel execution in nonce generation is a good practice for performance optimization.
373-376: Continuation of parallel execution logic in nonce generation is consistent with the earlier part of the method and is a good practice.
407-410: The use of a read lock on
noncesMuin thegenerateNoncesIfNecessarymethod is a good practice for thread safety.434-437: The
getNoncemethod's encryption and signing logic aligns with the security requirements of the system.451-454: The check for the presence of a signature in the
setNoncemethod is a necessary validation step.471-472: The use of the new constant
ErrUnexpectedStatein thesetNoncemethod's error message likely standardizes error messages.489-492: The
SetNoncesAndSignmethod has been updated with logic that aligns with the refactoring objectives.513-516: Continuation of the
SetNoncesAndSignmethod with thesignmethod call is consistent with the earlier part of the method and aligns with the refactoring objectives.signer/threshold_validator_test.go (14)
1-1: The package has been renamed to
signer_test, which is a common practice in Go to ensure that the tests are black-box tests, meaning they can only access exported names.11-19: New imports have been added to the file. It's important to ensure that these new packages are used in the test file and that the changes are consistent with the refactor.
47-50: The
MockValidatorstruct has been modified to embedsigner.ThresholdValidatorand include anonceCache. This change aligns with the refactor and seems to be correctly implemented.52-83: The
NewMockValidatorfunction has been modified to accept additional parameters and initializeMockValidatorwithsigner.NewThresholdValidator. Ensure that all calls to this function have been updated to pass the new parameters.Verification successful
The calls to
NewMockValidatorwithin thesigner/threshold_validator_test.gofile have been updated to include the new parameters, as shown in the output from the executed script.* 85-102: The `TestMain` function has been modified to set `testConfig` to a new instance of `config.RuntimeConfig`. This change is consistent with the introduction of the global variable `testConfig`.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for calls to NewMockValidator to ensure they pass the new parameters. ast-grep --lang go --pattern $'NewMockValidator($$$)'Length of output: 1207
104-116: The
TestThresholdValidator*functions have been modified to accepttestConfigas a parameter. This change is consistent with the refactor and the introduction of the globaltestConfig.22-129: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [119-137]
The
loadKeyForLocalCosignerfunction now accepts aconfig *config.RuntimeConfigparameter. This change is consistent with the refactor and should be verified to ensure that all calls to this function have been updated accordingly.Verification successful
The output from the script confirms the function definition of
loadKeyForLocalCosignerand shows that the last parameter is indeed of type*config.RuntimeConfig. The calls to this function found earlier in thesigner/threshold_validator_test.gofile are passing a variable namedcosignerConfigas the last argument, which is expected to be of type*config.RuntimeConfig.Given this information, it can be inferred that the variable
cosignerConfigis of the correct type, and the calls toloadKeyForLocalCosignerhave been updated accordingly to pass this new parameter as part of the refactor. Therefore, the change to theloadKeyForLocalCosignerfunction is verified to be consistent with the refactor.* 139-139: The `testThresholdValidator` function now accepts a `configuration *config.RuntimeConfig` parameter. This change is consistent with the refactor and the introduction of the global `testConfig`.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for calls to loadKeyForLocalCosigner to ensure they pass the new config parameter. ast-grep --lang go --pattern $'loadKeyForLocalCosigner($$$)'Length of output: 358
Script:
#!/bin/bash # Check the type of `cosignerConfig` to confirm it matches `*config.RuntimeConfig` ast-grep --lang go --pattern $'var cosignerConfig $_'Length of output: 54
Script:
#!/bin/bash # Broaden the search to find any assignment or declaration of `cosignerConfig` to infer its type. ast-grep --lang go --pattern $'$_ := cosignerConfig'Length of output: 53
Script:
#!/bin/bash # Search for the function definition of `loadKeyForLocalCosigner` to check the parameter types. ast-grep --lang go --pattern $'func loadKeyForLocalCosigner($$$)'Length of output: 1318
372-375: The
getTestLocalCosignersfunction has been modified, but the changes are not visible in the hunk. It's important to ensure that the changes are consistent with the refactor and that the function is still functioning as expected.392-398: The
cosignersConfigvariable is being initialized with a new configuration. This change is consistent with the refactor and should be verified to ensure that the configuration is correctly used throughout the tests.405-414: A new
RuntimeConfigis being created for each cosigner. This change is consistent with the refactor and the introduction of the globaltestConfig.416-423: The
NewLocalCosignerfunction is being called with new parameters. This change is consistent with the refactor and should be verified to ensure that all calls to this function have been updated accordingly.432-437: The
loadKeyForLocalCosignerfunction is being called twice with the newcosignerConfigparameter. This change is consistent with the refactor and the modifications to the function signature.429-478: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [442-655]
The
testThresholdValidatorLeaderElectionfunction has been commented out. This could be for various reasons, such as the function being deprecated or the functionality being tested elsewhere. It's important to verify the reason for this change and ensure that the functionality is still adequately tested.signer/threshold_validator.go (32)
9-9: The addition of the
stringspackage suggests new string manipulation operations have been introduced. Ensure that these operations are necessary and correctly implemented.32-43: The
nodecacheconfigsstruct andnodecacheconfigfunction have been added to configure node cache settings. Verify that the default values used here are appropriate and that they are being used consistently throughout the application.49-59: The
ThresholdValidatorstruct has been refactored to use interfaces for better abstraction and flexibility. Ensure that all implementations of these interfaces are consistent with their expected behavior.79-90: The new error type
StillWaitingForBlockErrorhas been added. Ensure that this error is being handled appropriately wherever it is used.116-132: The
BeyondBlockErrorerror type and its generation function have been added. Verify that the error message provides enough context for debugging and that the error is being handled correctly in all relevant parts of the code.138-154: The
NewThresholdValidatorfunction has been refactored to use interfaces and new configurations. Ensure that the function correctly initializes all members of theThresholdValidatorstruct, especially the newly introduced interfaces.188-188: The
StartNoncePrunermethod is being called onMyCosigner. Verify that this method exists on theLocalCosignertype and that it is safe to call it in this context without additional checks.229-232: The
SaveLastSignedStateInitiatedmethod is being called without error handling. Ensure that any errors returned by this method are handled appropriately.243-243: The
newBeyondBlockErrormethod is being used to generate an error. Verify that this method is implemented correctly and that the error is being handled appropriately in the calling context.277-280: The
CondWaitWithTimeoutmethod is being used onlastSignState. Verify that this method is implemented correctly and that the condition variable is being used appropriately to synchronize state.320-323: The
notifyBlockSignErrormethod is being introduced. Ensure that this method is implemented correctly and that it is being called in all appropriate error handling paths.345-345: The
WaitForSignStatesToFlushToDiskmethod is being called onMyCosigner. Verify that this method exists on theLocalCosignertype and that it is safe to call it in this context without additional checks.351-354: The
GetPubKeymethod is being called onMyCosigner. Ensure that this method is implemented correctly and that the public key is being handled securely.368-379: The
LoadSignStateIfNecessarymethod has been updated. Verify that the new implementation correctly handles the sign state and that theos.DevNullusage is appropriate.395-395: The
compareBlockSignatureAgainstHRSfunction is being called without error handling. Ensure that any errors returned by this function are handled appropriately.438-447: The
compareBlockSignatureAgainstHRSfunction has been introduced. Ensure that the logic for comparing block signatures is correct and that the error handling is appropriate.459-466: The
getNoncesFallbackmethod is being introduced. Verify that this method correctly handles the retrieval of nonces and that the error handling is appropriate.472-476: The
allCosignersslice is being created with an assumption about the size ofpeerCosigners. Ensure that this assumption is valid and that the slice is being used correctly.493-499: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [486-499]
The
thresholdNoncesandthresholdCosignersare being populated in a loop. Verify that the logic for collecting nonces and cosigners is correct and that the resulting data structures are used appropriately.
519-522: The
waitForPeerNoncesmethod is being introduced. Ensure that this method correctly waits for nonces from peers and that the error handling is appropriate.566-567: The
metrics.TotalRaftLeaderElectionTimeoutmetric is being incremented. Verify that this metric is being used correctly and that it accurately reflects the state of the raft leader election.582-585: The
peerCosigners.GetByIndexmethod is being called. Ensure that this method is implemented correctly and that the error handling is appropriate if the cosigner is not found.587-590: The
Signmethod is being called on aRemoteCosigner. Verify that this method is implemented correctly and that the error handling is appropriate.596-596: The
BeyondBlockErroris being created from an RPC error message. Verify that this conversion is correct and that the error handling is appropriate.605-609: The
Signfunction is being refactored. Verify that the refactoring maintains the correct behavior and that the error handling is appropriate.654-656: The comment suggests that a significant portion of the code should be moved to a different package. If this is a planned refactor, ensure that it is tracked in the project's issues or roadmap.
736-738: The
ClearNoncesmethod is being called onnonceCache. Verify that this method is implemented correctly and that it is being used appropriately in the error handling path.745-746: The
cosignerHealth.MarkUnhealthymethod is being called. Ensure that this method is implemented correctly and that it is being used appropriately to mark cosigners as unhealthy.803-806: The
CombineSignaturesmethod is being called onMyCosigner. Verify that this method is implemented correctly and that the combined signature is being handled securely.810-813: The
VerifySignaturemethod is being called onMyCosigner. Ensure that this method is implemented correctly and that the signature verification is secure.837-838: The
notifyBlockSignErrormethod is being called in the error handling path. Verify that this method is implemented correctly and that it is being used appropriately.852-852: The
metrics.TimedSignBlockLagmetric is being observed. Verify that this metric is being used correctly and that it accurately reflects the time taken to sign a block.
pkg/cosigner/icosigner.go
Outdated
| type iCosigner interface { | ||
| Health() | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The interface iCosigner is defined with a single method Health(). Ensure that this method is implemented wherever the iCosigner interface is used. Also, consider adding comments to the interface and its method to explain their purpose and usage.
pkg/tss/types.go
Outdated
| type Address = cometbytes.HexBytes | ||
|
|
||
| type PubKey interface { | ||
| Address() Address | ||
| Bytes() []byte | ||
| VerifySignature(msg []byte, sig []byte) bool | ||
| // Equals(PubKey) bool | ||
| Type() string |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The PubKey interface is correctly defined with methods that are typical for public key operations. However, the commented Equals method suggests that it may be needed for comparing public keys. If this functionality is required, it should be uncommented and implemented.
// Uncomment the Equals method if comparison of public keys is necessary.
// Equals(PubKey) bool| // Ed25519Key is a single Ed255219 key shard for an m-of-n threshold signer. | ||
| // TODO: This should be renamed to SignerEd25519 and tbh Private shard should private. | ||
| type PersistentEd25519Key struct { | ||
| pubKey PubKey // Public key of the persistent shard. Pubkey is the same for all shards. | ||
| privateShard []byte // | ||
| index int // Shamir index of this shard | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The PersistentEd25519Key struct is defined with a TODO comment suggesting a rename and privacy change for the privateShard field. This should be addressed before merging to ensure clarity and proper encapsulation.
// TODO: Rename `PersistentEd25519Key` to `SignerEd25519` and make `privateShard` private.|
|
||
| // CosignerSecurity is an interface for the security layer of the cosigner. | ||
| type CosignerSecurity interface { | ||
| type ICosignerSecurity interface { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 NOTE
Codebase verification is a beta feature.
The verification process has revealed that the old interface name CosignerSecurity is still present in the codebase alongside the new interface name ICosignerSecurity. This suggests that the renaming process is incomplete. It is recommended to update all references to the old interface name to ensure consistency and avoid potential compilation errors.
Analysis chain
The interface ICosignerSecurity has been renamed from CosignerSecurity. Ensure that all references to this interface throughout the codebase are updated to reflect the new name.
Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for old interface name usage.
rg --type go 'CosignerSecurity'
# Search for new interface name usage.
rg --type go 'ICosignerSecurity'
Length of output: 6026
signer/raft_store.go
Outdated
|
|
||
| func (s *RaftStore) SetThresholdValidator(thresholdValidator *ThresholdValidator) { | ||
| s.thresholdValidator = thresholdValidator | ||
| s.thresholdValidator.MyCosigner = s.mycosigner // TODO: Refactor out the use of cosigner. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The TODO comment suggests refactoring away from the use of the mycosigner field. Consider creating a task or issue to track this technical debt for future refactoring.
| var ( | ||
| testConfig *config.RuntimeConfig // use this global config in tests | ||
| ) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The introduction of a global variable testConfig is a significant change. Using global state can make tests less predictable and harder to parallelize. It's important to ensure that this global state does not introduce any unintended side effects.
pkg/cosigner/server.go
Outdated
| // TODO: This should only generate nonces for the cosigners that are online | ||
| // although it might doesnt matter if we arent doing DKG | ||
| // Should call an interface: dealnonce or something | ||
| nonces, err := tss.NonceGenerator{}.GenerateNonces( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The use of tss.NonceGenerator is approved. However, the TODO comment suggests an improvement that should be addressed in future iterations.
| // func (cosigner *RemoteCosigner) GetPubKey(_ string) (cometcrypto.PubKey, error) { | ||
| // return nil, fmt.Errorf("unexpected call to RemoteCosigner.GetPubKey") | ||
| // } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The GetPubKey method has been commented out. If this method is no longer needed, it should be removed. If it is temporarily disabled, ensure that there is a tracking issue or comment explaining why.
| // return false | ||
| // } | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The VerifySignature method has been commented out. Similar to the GetPubKey method, ensure that there is a clear reason for this and that it is tracked or documented.
| func NewSingleSignerValidator(config *config.RuntimeConfig) *SingleSignerValidator { | ||
| return &SingleSignerValidator{ | ||
| config: config, | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 NOTE
Codebase verification is a beta feature.
The usage of NewSingleSignerValidator in cmd/horcrux/cmd/start.go is incorrect as per the updated signature in the signer package. The function now expects a single argument of type *config.RuntimeConfig, but it is being called with two arguments out, acceptRisk. This needs to be corrected to match the new function signature.
Analysis chain
The NewSingleSignerValidator function has been updated to accept a *config.RuntimeConfig. Verify that all instances of this function are updated to pass the correct configuration type.
Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for usages of the NewSingleSignerValidator function.
rg --type go 'NewSingleSignerValidator'
Length of output: 715
Script:
#!/bin/bash
# Check the signature of NewSingleSignerValidator function in cmd/horcrux/cmd/start.go
rg --type go -A 3 'func NewSingleSignerValidator' cmd/horcrux/cmd/start.go
Length of output: 76
Script:
#!/bin/bash
# Check the import statements in cmd/horcrux/cmd/start.go to see if it's importing the signer package.
rg --type go '^import' -A 10 cmd/horcrux/cmd/start.go
Length of output: 369
|
@coderabbitai review |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 13
Configuration used: CodeRabbit UI
Files selected for processing (13)
- pkg/cosigner/cosigner.go (1 hunks)
- pkg/cosigner/icosigner.go (1 hunks)
- pkg/cosigner/ithresholdsigner.go (1 hunks)
- pkg/cosigner/server.go (21 hunks)
- pkg/cosigner/types.go (1 hunks)
- pkg/tss/doc.go (1 hunks)
- pkg/tss/ted25519/threshold-ed25519_signer_soft.go (1 hunks)
- pkg/tss/threshold_signer.go (1 hunks)
- pkg/tss/types.go (1 hunks)
- signer/cosigner_nonce_cache.go (12 hunks)
- signer/icosigner.go (1 hunks)
- signer/threshold_validator.go (30 hunks)
- test/validator_threshold.go (7 hunks)
Additional comments: 64
pkg/cosigner/icosigner.go (1)
- 1-1: The package name change from
signertocosigneris consistent with the PR's objective to refactor and reorganize code for clarity.pkg/cosigner/ithresholdsigner.go (1)
- 1-25: The package name change and updated import paths align with the PR's refactoring goals. Ensure that the new interfaces
IThresholdSigner,IThresholdDealer, andIThresholdare correctly implemented throughout the codebase.pkg/tss/doc.go (1)
- 1-45: The package documentation provides a clear overview of the
tsspackage's purpose and usage, which is beneficial for maintainability and understanding of the codebase.pkg/cosigner/cosigner.go (1)
- 1-101: The package name change and updated import paths align with the PR's refactoring goals. Ensure that the
MPCstruct and its methods are correctly implemented and used throughout the codebase.Verification successful
The
MPCstruct and its methodsSign,Stop, andStartare defined inpkg/cosigner/cosigner.go. References toMPCin other files suggest that it is used across the codebase, particularly in the signing process. To ensure consistency, we should verify that the changes incosigner.goare compatible with howMPCis used elsewhere.
The
MPCstruct inpkg/cosigner/cosigner.gois correctly defined with appropriate fields and interfaces. The methodsSign,Stop, andStartare stubbed with no implementation, which is acceptable if the logic is to be added later or elsewhere.The references to
MPCinsigner/threshold_validator.goandcmd/horcrux/cmd/single_signer.goindicate thatMPCis indeed used across the codebase, particularly in the signing process. The comments insigner/threshold_validator.gosuggest thatMPCis central to the multi-party computation/communication process.Based on the provided context, there are no inconsistencies or issues with the
MPCstruct and its methods. The usage ofMPCin other parts of the codebase appears to be consistent with the changes made incosigner.go.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the MPC struct and its methods are implemented correctly. rg --type go "MPC"Length of output: 1201
Script:
#!/bin/bash # Verify the correct implementation of the MPC struct and its methods in cosigner.go ast-grep --lang go --pattern $'type MPC struct { $$$ }' # Verify the usage of the MPC struct in other parts of the codebase to ensure consistency rg --type go -A 3 "MPC"Length of output: 4579
pkg/cosigner/types.go (1)
- 1-116: The package name change and updated import paths align with the PR's refactoring goals. Ensure that the new types and conversion methods are correctly implemented and used throughout the codebase.
Verification successful
To verify the correct implementation and usage of the new types and conversion methods, we will focus on a few instances of each type. Starting with
SignatureRequestandSignatureResponse, we will check their usage in the codebase.
The output indicates that
SignatureRequestandSignatureResponseare indeed being used in the codebase. TheSignatureRequeststruct is used as a parameter for thesignfunction inpkg/cosigner/server.go, andSignatureResponseis used as the return type for the same function. Additionally,SignatureResponseis returned from theSetNoncesAndSignfunction in multiple files, such aspkg/cosigner/server.go,pkg/cosigner/cosigner.go, andpkg/cosigner/client.go.This usage suggests that the new types are correctly implemented and integrated into the codebase's signing process. Next, we should verify the usage of
Nonceand related conversion methods.
The output shows that the
Noncetype and its related conversion methodstoProtoandFromProtoToNonceare used throughout the codebase. TheNoncetype is used in various contexts, including signing operations, nonce generation, and gRPC message structures. The conversion methods are used to convert between theNoncetype and its protocol buffer representation, which is essential for network communication between different components of the system.The usage of
Noncein thesignfunction, as well as in theSetNoncesAndSignandGetNoncesmethods, indicates that nonces are being handled as part of the signing process. The presence of these types and methods in both thepkg/cosignerpackage and thesignerpackage, as well as in the protocol buffer definitions (signer/proto/cosigner.pb.go), suggests that the implementation is consistent with the intended refactoring and that the new types and methods are integrated correctly for their purposes.Next, we should verify the usage of
CosignerUUIDNoncesand related conversion methods.
The output shows that
CosignerUUIDNoncesand theToProtomethod are used in various parts of the codebase. TheCosignerUUIDNoncestype is used to handle nonces associated with a UUID, which is a common pattern in distributed systems to ensure the uniqueness of requests or sessions.The
ToProtomethod is used to convert theCosignerUUIDNoncestype to its protocol buffer representation, which is necessary for serialization and network communication. This method is found in thepkg/cosigner/types.gofile and is used in theCosignerUUIDNoncesMultipletype, which is a slice ofCosignerUUIDNonces. This slice is then converted to a slice of protocol buffer messages, which is used in gRPC communication, as seen in thesigner/cosigner_grpc_server.gofile.The usage of
CosignerUUIDNoncesin theGetNoncesandSetNoncesAndSignmethods across different files such aspkg/cosigner/server.go,pkg/cosigner/client.go, andsigner/threshold_validator.goindicates that these nonces are part of the core functionality related to cosigner operations.The presence of
ToProtoconversions in other unrelated types likeHRSTandBlockinpkg/types/hrs.goandpkg/types/block.gosuggests that theToProtonaming convention is a standard practice in the codebase for converting types to their protocol buffer equivalents.Based on the output, it appears that
CosignerUUIDNoncesand the related conversion methods are correctly implemented and used in the codebase, aligning with the refactoring goals of the PR.The verification of
SignatureRequest,SignatureResponse,Nonce, andCosignerUUIDNoncesalong with their associated conversion methods suggests that the changes are correctly implemented and used throughout the codebase.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the new types and conversion methods are implemented correctly. rg --type go "SignatureRequest|SignatureResponse|Nonce|CosignerUUIDNonces|CosignerSetNoncesAndSignRequest"Length of output: 44178
Script:
#!/bin/bash # Check the usage of SignatureRequest and SignatureResponse in the codebase. rg --type go "SignatureRequest|SignatureResponse"Length of output: 1000
Script:
#!/bin/bash # Check the usage of Nonce and related conversion methods in the codebase. rg --type go "Nonce|toProto|FromProtoToNonce"Length of output: 43685
Script:
#!/bin/bash # Check the usage of CosignerUUIDNonces and related conversion methods in the codebase. rg --type go "CosignerUUIDNonces|ToProto"Length of output: 2222
pkg/tss/threshold_signer.go (1)
- 1-122: The package name change and updated import paths align with the PR's refactoring goals. Ensure that the new functions and types are correctly implemented and used throughout the codebase.
Verification successful
The new functions and types added to
pkg/tss/threshold_signer.goare correctly implemented and are being used in other parts of the codebase as well.
NewThresholdEd25519SignerSoftis used inpkg/cosigner/server.go.LoadVaultKeyFromFileis used incmd/horcrux/cmd/address.go.CreatePersistentEd25519ThresholdSignShardsFromFileis used incmd/horcrux/cmd/shards.go.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the new functions and types are implemented correctly. rg --type go "NewThresholdEd25519SignerSoft|LoadVaultKeyFromFile|CreatePersistentEd25519ThresholdSignShardsFromFile|generatePersistentThresholdSignShards"Length of output: 1548
pkg/tss/types.go (1)
- 1-159: The package name change and updated import paths align with the PR's refactoring goals. Ensure that the new types and methods are correctly implemented and used throughout the codebase.
Verification successful
To verify the correct implementation and usage of the new types and methods, we need to look at how they are constructed and used in the codebase.
The ast-grep command did not provide information about the constructors or state-modifying methods for the types
PersistentEd25519Key,Ed25519Key, andVaultKey. We need to refine the pattern to match these specific types. The rg command output shows theReadCometBFTPrivValidatorFileandWriteToFilefunctions are implemented and used in the codebase.Let's refine the ast-grep pattern to match the specific types and confirm the usage of the functions.
The ast-grep command did not provide the expected results for the types
PersistentEd25519Key,Ed25519Key, andVaultKey. We will use ripgrep to search for the constructors or methods that modify the state of these types. The rg command output shows theReadCometBFTPrivValidatorFileandWriteToFilefunctions are implemented and used in the codebase, which is consistent with their definitions.Let's proceed with ripgrep to search for the constructors or methods related to the types.
The output from the ripgrep command provides us with instances where the types
Ed25519KeyandVaultKeyare used in function signatures and methods. Here are the findings:
Ed25519Keyhas methodsID,MarshalJSON, andUnmarshalJSONdefined inpkg/tss/types.go.LoadVaultKeyFromFilereturns anEd25519Keyand is defined inpkg/tss/threshold_signer.go.CreatePersistentEd25519ThresholdSignShardsFromFilereturns a slice ofVaultKeyand is also defined inpkg/tss/threshold_signer.go.GeneratePersistentThresholdSignShardsis a generic function that takesEd25519Keyas a type parameter.generatePersistentThresholdSignShardsreturns a slice ofVaultKey.getShardedPrivvalKeyreturns a slice ofEd25519Keyintest/validator_threshold.go.No constructors or state-modifying methods for
PersistentEd25519Keywere found, which might imply that it is not instantiated directly or modified through methods in the current codebase, or such methods are not named with a standard constructor pattern.The usage of
ReadCometBFTPrivValidatorFileandWriteToFilefunctions is consistent with their definitions based on the previous rg command output.Based on the information gathered, the new types and methods seem to be correctly implemented and used throughout the codebase, with the caveat that we did not find specific constructors or state-modifying methods for
PersistentEd25519Key.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the new types and methods are implemented correctly. rg --type go "PersistentEd25519Key|Ed25519Key|VaultKey|ReadCometBFTPrivValidatorFile|WriteToFile"Length of output: 4148
Script:
#!/bin/bash # Check the implementation of PersistentEd25519Key, Ed25519Key, and VaultKey by looking at their constructors or methods that modify their state. ast-grep --lang go --pattern $'type $_ { $$$ }' | grep -E 'PersistentEd25519Key|Ed25519Key|VaultKey' # Check the usage of ReadCometBFTPrivValidatorFile and WriteToFile functions to ensure they are used correctly. rg --type go -A 3 "ReadCometBFTPrivValidatorFile|WriteToFile"Length of output: 1826
Script:
#!/bin/bash # Refine the ast-grep pattern to match the specific types PersistentEd25519Key, Ed25519Key, and VaultKey. ast-grep --lang go --pattern $'type PersistentEd25519Key { $$$ }' ast-grep --lang go --pattern $'type Ed25519Key { $$$ }' ast-grep --lang go --pattern $'type VaultKey { $$$ }' # Confirm that the usage of ReadCometBFTPrivValidatorFile and WriteToFile functions is consistent with their definitions. rg --type go -C 3 "ReadCometBFTPrivValidatorFile" rg --type go -C 3 "WriteToFile"Length of output: 3247
Script:
#!/bin/bash # Use ripgrep to search for the constructors or methods that modify the state of PersistentEd25519Key, Ed25519Key, and VaultKey. rg --type go "func NewPersistentEd25519Key|func NewEd25519Key|func NewVaultKey|func .*PersistentEd25519Key|func .*Ed25519Key|func .*VaultKey"Length of output: 1098
pkg/tss/ted25519/threshold-ed25519_signer_soft.go (1)
- 30-41: Verify whether the
AssymetricKeyandAssymetricKeyShardtypes are used elsewhere in the codebase or if they are remnants of dead code.Verification successful
The search results indicate that the
AssymetricKeyandAssymetricKeyShardtypes are defined in two files within the codebase:
pkg/tss/types.gopkg/tss/ted25519/threshold-ed25519_signer_soft.goSince the types are present in
types.go, it suggests that they are part of the types definitions for the package and are likely intended to be used by other parts of the codebase, not just withinthreshold-ed25519_signer_soft.go. This implies that the types are not dead code within the context of the entire codebase.Based on the information provided by the script output:
Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for usage of AssymetricKey and AssymetricKeyShard rg --type go 'AssymetricKey' rg --type go 'AssymetricKeyShard'Length of output: 548
test/validator_threshold.go (7)
12-17: Updated import paths to reflect the new package structure.
32-37: Ensure that the new parameter
totalSentriesis being used correctly within the function and that all calls to this function have been updated to include this new parameter.Verification successful
The calls to the function
testChainSingleNodeAndHorcruxThresholdintest/horcrux_test.gohave been updated to include the newtotalSentriesparameter, as evidenced by the output from thergcommand which shows the function being called with five parameters.* 55-60: Similar to the previous comment, ensure that the new parameter `totalSentries` is being used correctly within the function and that all calls to this function have been updated to include this new parameter.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for the function `testChainSingleNodeAndHorcruxThreshold` to verify the usage of the new parameter. ast-grep --lang go --pattern $'func testChainSingleNodeAndHorcruxThreshold($_, $_, $_, $_, $_, $_, $_) { $$$ }'Length of output: 112
Script:
#!/bin/bash # Search for the function `testChainSingleNodeAndHorcruxThreshold` without specifying the number of parameters to verify its existence and usage. ast-grep --lang go --pattern $'func testChainSingleNodeAndHorcruxThreshold($$$) { $$$ }'Length of output: 1725
Script:
#!/bin/bash # Search for calls to the function `testChainSingleNodeAndHorcruxThreshold` to verify if the new parameter `totalSentries` is included. rg "testChainSingleNodeAndHorcruxThreshold\("Length of output: 831
Verification successful
To verify the correct usage of the new parameter
totalSentriesand to ensure that all calls to the functionstartChainSingleNodeAndHorcruxThresholdhave been updated, I will perform a search using ripgrep to find the function definition and its calls within the codebase.
To further verify the usage of the
totalSentriesparameter and to check if all calls to the functionstartChainSingleNodeAndHorcruxThresholdhave been updated, I will generate a script to extract the full function signature and to find all occurrences of this function being called.
The output from the scripts provides the following information:
- The function
startChainSingleNodeAndHorcruxThresholdis defined intest/validator_threshold.gowith the parametersctx,t,totalValidators,totalSigners,threshold,totalSentries, andsentriesPerSigner.- Calls to
startChainSingleNodeAndHorcruxThresholdare found intest/validator_threshold.goandtest/horcrux_test.go, with all the required parameters, including the newtotalSentriesparameter.Based on this information, it can be concluded that the new parameter
totalSentriesis being used correctly within the function and that all calls to this function have been updated to include this new parameter.* 187-203: Verify that the new types and functions from the `nodesecurity` and `config` packages are being used correctly in the `convertValidatorToHorcrux` function.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for the function `startChainSingleNodeAndHorcruxThreshold` to verify the usage of the new parameter. ast-grep --lang go --pattern $'func startChainSingleNodeAndHorcruxThreshold($_, $_, $_, $_, $_, $_, $_) { $$$ }'Length of output: 113
Script:
#!/bin/bash # Search for the function definition and its calls in the codebase. rg "func startChainSingleNodeAndHorcruxThreshold"Length of output: 125
Script:
#!/bin/bash # Extract the full function signature and search for calls to the function. rg -A 3 "func startChainSingleNodeAndHorcruxThreshold" test/validator_threshold.go rg "startChainSingleNodeAndHorcruxThreshold" -C 3Length of output: 2496
- 211-223: Verify that the new
configstruct is being used correctly and that all instances of its usage have been updated.Verification successful
The
config.Configstruct is being used in thetest/validator_threshold.gofile, as shown in the output from the ast-grep command. The instantiation at lines 218-228 intest/validator_threshold.gomatches the snippet provided in the review comment, indicating that the struct is being used with the new fields and types as part of the refactor.
- The
SignModeis set toconfig.SignModeThreshold.- The
ThresholdModeConfigis a pointer to a newconfig.ThresholdModeConfigstruct with fieldsThreshold,Cosigners,GRPCTimeout, andRaftTimeout.- The
ChainNodesfield is populated with a slice ofconfig.ChainNodestructs.- The
DebugAddrfield is set usingfmt.Sprintf.Based on the provided output, it appears that the new
configstruct is being used correctly in the context of thetest/validator_threshold.gofile.* 256-270: Verify that the new types and functions from the `tss` package are being used correctly in the `getShardedPrivvalKey` function and related code.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for the usage of `config.Config` to ensure it is used correctly. ast-grep --lang go --pattern $'config.Config{$$$}'Length of output: 15518
Verification successful
Based on the output from the shell scripts, the function
tss.GeneratePersistentThresholdSignShardsis used intest/validator_threshold.go, and the typetss.Ed25519Keyis used in several test files and a migration command file. The usage intest/validator_threshold.gomatches the expected pattern of passing four arguments to the function, which suggests correct usage in that instance.The
tss.Ed25519Keytype is instantiated with fieldsPubKey,PrivateShard, andIDin various test files and a migration command, which also suggests correct usage based on the provided fields.Given this information, the new types and functions from the
tsspackage appear to be used correctly in thegetShardedPrivvalKeyfunction and related code.* 338-341: Verify that the logic for distributing sentries to cosigners in the `getSentriesForCosignerConnection` function is correct and that it handles edge cases properly.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for the usage of `tss.GeneratePersistentThresholdSignShards` and `tss.Ed25519Key` to ensure they are used correctly. ast-grep --lang go --pattern $'tss.GeneratePersistentThresholdSignShards($_, $_, $_, $_)' ast-grep --lang go --pattern $'tss.Ed25519Key{$$$}'Length of output: 1523
pkg/cosigner/server.go (16)
1-1: Renamed package from
signertocosigneraligns with the PR's objective to refactor and reorganize code.10-13: Updated import paths to reflect the new package structure. Ensure that these new paths are correct and the packages exist at the specified locations.
Verification successful
The shell script output confirms that the directories for the
config,metrics, andtsspackages exist within thepkgdirectory. This verifies that the updated import paths in thepkg/cosigner/server.gofile are correct and the packages are located at the specified paths.
* 29-29: Introduced a new constant `ErrUnexpectedState`. Ensure that this constant is used consistently throughout the codebase.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the new import paths are valid. fd 'config|metrics|tss' --type dLength of output: 68
Verification successful
The constant
ErrUnexpectedStateis defined inpkg/cosigner/server.goand is used insigner/threshold_validator.goto check for a specific error condition. This indicates that the constant is being utilized consistently within the codebase.
* 36-47: Changes to the `LocalCosigner` struct fields to use new types from the `config` package and the introduction of the `dealer` field. Ensure that all references to these fields are updated accordingly.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for usage of the new constant ErrUnexpectedState. rg 'ErrUnexpectedState' --type goLength of output: 279
Verification successful
The
rgcommand has provided instances where thedealerfield is mentioned in theserver.gofile. Here are the findings:
- The
dealerfield is declared within theLocalCosignerstruct, indicating that it is indeed a part of the struct's definition.- There is a commented-out line where
dealerappears to be used as a field within another struct, but it's commented and thus not active in the code.- The
dealerfield is used in a method implementation wherecosigner.dealer.KeyGeneratoris called, which suggests that thedealerfield is being utilized in the codebase.Based on the provided output, it appears that the
dealerfield is both present in theLocalCosignerstruct and actively used in at least one method. Therefore, the review comment regarding the introduction of thedealerfield and ensuring that all references to these fields are updated accordingly seems to be addressed correctly in the codebase.* 71-75: The `signer` field has been renamed to `dealer` in the `ChainState` struct, and the old `dealer` field is commented out. Ensure that the `dealer` field is used correctly and the commented-out field is either removed or updated.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that all references to the changed struct fields are updated. ast-grep --lang go --pattern $'LocalCosigner { $$$ config: $_, $$$ security: $_, $$$ dealer: $_, $$$ }'Length of output: 104
Script:
#!/bin/bash # Verify that all references to the changed struct fields are updated by looking for usages of the LocalCosigner struct. ast-grep --lang go --pattern $'LocalCosigner { $$$ }'Length of output: 421
Script:
#!/bin/bash # Verify the usage of the 'dealer' field in the LocalCosigner struct. ast-grep --lang go --pattern $'LocalCosigner { $$$ dealer: $_, $$$ }'Length of output: 70
Script:
#!/bin/bash # Check for method implementations or struct initializations that reference the 'dealer' field. rg "dealer" --context 5Length of output: 1921
- 145-147: Added a new method
WaitForSignStatesToFlushToDiskto theLocalCosignertype. Ensure that this method is called at the appropriate places to avoid data races or inconsistencies during shutdown or restarts.Verification successful
The provided context shows that the
WaitForSignStatesToFlushToDiskmethod is called within theStopmethod of theThresholdValidatortype. This is a typical pattern for ensuring that any pending state is persisted before the object is stopped, which aligns with the intent expressed in the review comment to avoid data races or inconsistencies during shutdown or restarts.
- The
Stopmethod is designed to safely shut down theThresholdValidator.- Within
Stop, there is a call to a private methodwaitForSignStatesToFlushToDisk.- This private method calls
Waiton async.WaitGroup(pv.pendingDiskWG.Wait()) and then callsWaitForSignStatesToFlushToDiskonpv.MyCosigner.This indicates that the
WaitForSignStatesToFlushToDiskmethod is indeed being used in a shutdown context, which is appropriate for its intended purpose.* 191-191: The `GetPubKey` method now uses the `signer` field from the `ChainState` struct. Ensure that the `signer` field is correctly initialized and that the public key retrieval is consistent with the new structure.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for calls to the new method WaitForSignStatesToFlushToDisk. rg 'WaitForSignStatesToFlushToDisk' --type goLength of output: 394
Script:
#!/bin/bash # Display the surrounding code in signer/threshold_validator.go where WaitForSignStatesToFlushToDisk is called. rg -C 10 'WaitForSignStatesToFlushToDisk' signer/threshold_validator.goLength of output: 721
220-220: The
VerifySignaturemethod implementation has been updated to use the newsignerfield. Ensure that the signature verification logic is correct and that thesignerfield is properly initialized.326-330: The
LoadSignStateIfNecessarymethod now initializes asignerof typeIThresholdSigner. Ensure that the initialization is correct and that error handling is robust.Verification successful
The initialization of the
signerof typeIThresholdSignerwithin theLoadSignStateIfNecessarymethod is correctly performed, and the error handling is robust, as any error that occurs during the initialization results in the error being returned immediately.* 345-345: The `GetNonces` method has been updated with metric tracking. Verify that metric tracking is implemented correctly and consistently.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the signer initialization is correct in LoadSignStateIfNecessary. ast-grep --lang go --pattern $'func (cosigner *LocalCosigner) LoadSignStateIfNecessary($_) $_ { $$$ }'Length of output: 1513
Verification successful
The metric tracking in the
GetNoncesmethod, as indicated by the linemetrics.MetricsTimeKeeper.SetPreviousLocalNonce(time.Now()), is consistent with the rest of the codebase. TheMetricsTimeKeeperis used in a similar manner in other parts of the code to set timestamps for various events, such as local sign start, local sign finish, prevote, and precommit.
* 362-366: The `generateNoncesIfNecessary` method has been updated to handle nonce generation. Ensure that the logic for generating nonces only when necessary is correct and efficient.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that metric tracking in the GetNonces method is consistent with the rest of the codebase. rg 'MetricsTimeKeeper' --type goLength of output: 636
Verification successful
The
generateNoncesIfNecessarymethod inpkg/cosigner/server.gocorrectly implements the logic to generate nonces only when necessary. It first checks if nonces already exist for a given UUID and returns them if so. If nonces do not exist, it generates new ones, sets an expiration time, and then stores and returns them.
* 431-434: The `generateNoncesIfNecessary` method locks the `nonces` map for writing. Ensure that the locking is done correctly to prevent data races.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the logic for generating nonces only when necessary is correct. ast-grep --lang go --pattern $'func (cosigner *LocalCosigner) generateNoncesIfNecessary($_) $_ { $$$ }'Length of output: 1395
Verification successful
The locking in the
generateNoncesIfNecessarymethod appears to be implemented correctly. The method uses a read lock to check if the nonces exist for a given UUID and then uses a write lock when setting the nonces. This is a standard pattern to prevent data races when accessing shared resources in concurrent environments.
- The
RLockis used to read from thenoncesmap.- If the nonces do not exist, a new nonce is generated.
- A write lock (
Lock) is then used to update thenoncesmap with the new nonce.This pattern ensures that the map is not being read while it is being updated, which would prevent data races.
* 443-444: The `getNonce` method has been updated. Ensure that the nonce retrieval logic is correct and that error handling is robust.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the locking in generateNoncesIfNecessary is done correctly. ast-grep --lang go --pattern $'func (cosigner *LocalCosigner) generateNoncesIfNecessary($_) $_ { $$$ }'Length of output: 1395
Verification successful
The
getNoncemethod in theLocalCosignertype performs the following steps:
- Initializes a zero value for
Nonce.- Retrieves the cosigner's index with
cosigner.GetIndex().- Accesses the cosigner's metadata from the
meta.Noncesslice using the retrieved index.- Calls
cosigner.security.EncryptAndSignwith the peer ID, the public key from the metadata, and the corresponding share.- Checks for an error from
EncryptAndSignand returns the zero value and the error if one occurred.- If no error occurred, returns the nonce and
nilfor the error.The error handling is robust as it immediately returns a zero value and the error if
EncryptAndSignfails.Based on the provided code snippet, the nonce retrieval logic and error handling appear to be correct.
* 458-461: The `setNonce` method has been updated to include signature verification. Ensure that the signature verification logic is correct and that error handling is robust.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the nonce retrieval logic in getNonce is correct. ast-grep --lang go --pattern $'func (cosigner *LocalCosigner) getNonce($_, $_) $_ { $$$ }'Length of output: 922
Verification successful
The
setNoncemethod inserver.goincludes a check for anilsignature and uses theDecryptAndVerifymethod for signature verification. Error handling is present for missing signatures, decryption and verification errors, and unexpected states. The verification logic appears to be correct based on the provided context.
* 478-479: The error message uses the new `ErrUnexpectedState` constant. Ensure that the error message is informative and consistent with the rest of the codebase.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the signature verification logic in setNonce is correct. ast-grep --lang go --pattern $'func (cosigner *LocalCosigner) setNonce($_, $_) $_ { $$$ }'Length of output: 2004
Verification successful
The error message associated with
ErrUnexpectedStateis "unexpected state, metadata does not exist for U:", which is informative and indicates a clear issue with missing metadata. Additionally, the error constant is used consistently within the codebase, as seen in thesigner/threshold_validator.gofile where it's checked in a conditional statement. Therefore, the use ofErrUnexpectedStatein the error message is approved and verified.* 493-499: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [496-520]Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the error message using ErrUnexpectedState is informative and consistent. rg 'ErrUnexpectedState' --type goLength of output: 279
The
SetNoncesAndSignmethod has been updated with new logic for setting nonces and signing. Ensure that the logic is correct and that error handling is robust.Verification successful
The
SetNoncesAndSignmethod's logic and error handling have been verified and appear to be correct. The method properly handles errors at each critical step, returning early if an error is encountered, and uses anerrgroup.Groupfor parallel nonce setting with appropriate error collection.
Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the logic in SetNoncesAndSign is correct. ast-grep --lang go --pattern $'func (cosigner *LocalCosigner) SetNoncesAndSign($_, $_) $_ { $$$ }'Length of output: 1835
signer/threshold_validator.go (33)
9-9: The addition of the
stringspackage suggests new string operations are introduced in the code.29-29: The
ThresholdValidatornow implements theconnector.IPrivValidatorinterface, which may have implications on how instances ofThresholdValidatorare used throughout the codebase.31-44: The
nodecacheconfigstype andnodecacheconfigfunction have been introduced. Ensure that the configuration values used here are consistent with the rest of the application and that the naming convention follows the project's standards.46-59: The
ThresholdValidatorstruct has been refactored with new fields and comments. It's important to ensure that the new fields are properly initialized and used throughout the codebase.79-90: New error type
StillWaitingForBlockErrorhas been added. Verify that this error is handled appropriately wherever it's used.116-132: New error type
BeyondBlockErrorhas been added. Verify that this error is handled appropriately wherever it's used.71-164: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [138-176]
The
NewThresholdValidatorfunction has been refactored with new parameters and initializations. Ensure that all calls to this function have been updated to pass the correct arguments.
188-188: The
StartNoncePrunermethod is called onMyCosigner. Verify that this method exists and is implemented correctly in theLocalCosignertype.223-232: The
saveLastSignedStateInitiatedfunction has been refactored. Ensure that the error handling and the conditions for returning nil are correct and consistent with the application's logic.243-243: The
newBeyondBlockErrorfunction is used to create an error when the block to be signed is beyond the current block. Verify that this error is handled correctly in all places where it could be returned.277-277: The
CondWaitWithTimeoutmethod is called onlastSignState. Verify that this method exists and is implemented correctly, and that the timeout duration is appropriate.320-320: The
notifyBlockSignErrorfunction is introduced to handle errors during the block signing process. Ensure that this function is called in all appropriate error scenarios.345-345: The
WaitForSignStatesToFlushToDiskmethod is called onMyCosigner. Verify that this method exists and is implemented correctly in theLocalCosignertype.351-351: The
GetPubKeyfunction has been refactored to use theMyCosigner'sGetPubKeymethod. Ensure that the public key is correctly retrieved and returned in the expected format.368-379: The
LoadSignStateIfNecessaryfunction has been refactored. Ensure that the new sign state is correctly initialized and stored, and that theLoadSignStateIfNecessarymethod onMyCosigneris correctly implemented.388-395: The
getExistingBlockSignaturefunction has been refactored. Ensure that the logic for retrieving and comparing block signatures is correct and that the error handling is appropriate.415-419: The
compareBlockSignatureAgainstHRSfunction is used withincompareBlockSignatureAgainstSSC. Verify that the error handling and logic for comparing block signatures are correct.438-447: The
compareBlockSignatureAgainstHRSfunction has been refactored. Ensure that the logic for comparing the HRS of the block and the signature is correct and that the error types returned are handled appropriately.459-466: The
getNoncesFallbackfunction is introduced to handle nonce retrieval when the primary method fails. Verify that this fallback mechanism is robust and that the error handling is appropriate.472-476: The
waitForPeerNoncesfunction has been refactored. Ensure that the logic for waiting for nonces from peers is correct and that the error handling is appropriate.493-499: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [486-499]
The
getNoncesFallbackfunction returns aCosignerUUIDNoncesstruct. Verify that this struct is used correctly and that the nonces are properly aggregated from the threshold cosigners.
519-527: The
waitForPeerNoncesfunction includes metrics tracking and error handling. Ensure that metrics are correctly incremented and that errors from peers are handled appropriately.566-572: The
proxyIfNecessaryfunction has been refactored. Verify that the logic for determining if the current validator is the leader and proxying the request if necessary is correct.587-590: The
proxyIfNecessaryfunction calls theSignmethod on aRemoteCosigner. Verify that this method is implemented correctly and that the request is properly proxied.596-596: The
proxyIfNecessaryfunction handles an RPC error by creating aBeyondBlockError. Verify that this error is handled correctly in all places where it could be returned.604-608: The
Signfunction has been refactored. Ensure that the logic for signing a block is correct and that the error handling is appropriate.645-648: The
saveLastSignedStateInitiatedfunction is called within theSignfunction. Verify that the logic for saving the last sign state initiated is correct and that the error handling is appropriate.696-700: Metrics are updated within the
Signfunction. Verify that the metrics are correctly incremented and that the timing measurements are accurate.713-766: The
Signfunction includes a loop for getting signatures from remote cosigners. Ensure that the error handling, retry logic, and metrics tracking are correct.794-816: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [776-803]
The
Signfunction assembles the final signature from partial signatures. Verify that the combination of signatures is correct and that the error handling is appropriate.
810-815: The
Signfunction verifies the combined signature before saving. Ensure that the verification logic is correct and that the error handling is appropriate.837-839: The
Signfunction handles an error when saving the last sign state. Verify that the error handling is correct and that thenotifyBlockSignErrorfunction is called appropriately.852-854: The
Signfunction includes metrics tracking for the entire sign block process. Verify that the metrics are correctly observed and that the timing measurements are accurate.
| // var _ IThresholdSigner = &ThresholdSignerSoft{} | ||
|
|
||
| // GenerateEd25519ThresholdSignShards creates a map of shards from a private key | ||
| func GenerateEd25519ThresholdSignShards(pv []byte, threshold, shards uint8) map[uint8][]byte { | ||
| privShards := tsed25519.DealShares(tsed25519.ExpandSecret(pv[:32]), threshold, shards) | ||
| // TODO: Check that the length of privShards is equal to the number of shards | ||
| // TODO: Check that the pubkey is the same for all shards | ||
| out := make(map[uint8][]byte, shards) | ||
| for id, shard := range privShards { | ||
| id := uint8(id + 1) | ||
| out[id] = shard | ||
| } | ||
| return out | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The TODO comments on lines 20 and 21 should be addressed or tracked in an issue tracker to ensure they are not forgotten.
- // TODO: Check that the length of privShards is equal to the number of shards
- // TODO: Check that the pubkey is the same for all shardsCommittable 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.
| // var _ IThresholdSigner = &ThresholdSignerSoft{} | |
| // GenerateEd25519ThresholdSignShards creates a map of shards from a private key | |
| func GenerateEd25519ThresholdSignShards(pv []byte, threshold, shards uint8) map[uint8][]byte { | |
| privShards := tsed25519.DealShares(tsed25519.ExpandSecret(pv[:32]), threshold, shards) | |
| // TODO: Check that the length of privShards is equal to the number of shards | |
| // TODO: Check that the pubkey is the same for all shards | |
| out := make(map[uint8][]byte, shards) | |
| for id, shard := range privShards { | |
| id := uint8(id + 1) | |
| out[id] = shard | |
| } | |
| return out | |
| } | |
| // var _ IThresholdSigner = &ThresholdSignerSoft{} | |
| // GenerateEd25519ThresholdSignShards creates a map of shards from a private key | |
| func GenerateEd25519ThresholdSignShards(pv []byte, threshold, shards uint8) map[uint8][]byte { | |
| privShards := tsed25519.DealShares(tsed25519.ExpandSecret(pv[:32]), threshold, shards) | |
| out := make(map[uint8][]byte, shards) | |
| for id, shard := range privShards { | |
| id := uint8(id + 1) | |
| out[id] = shard | |
| } | |
| return out | |
| } |
| // Sign signs a byte payload with the provided nonces. | ||
| // The return are a "partial signature". | ||
| func (s *Ted25519SignerSoft) Sign(nonces []types.Nonce, payload []byte) ([]byte, error) { | ||
| // sum the nonces to get the ephemeral public key and share | ||
| nonceShare, noncePub, err := sumNonces(nonces) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to combine nonces: %w", err) | ||
| } | ||
|
|
||
| sig := tsed25519.SignWithShare( | ||
| payload, s.privateKeyShard, nonceShare, s.pubKey, noncePub) | ||
| return append(noncePub, sig...), nil |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ensure that the Sign method's error messages are consistent and provide enough context for debugging. The error message on line 80 could be more descriptive.
- return nil, fmt.Errorf("failed to combine nonces: %w", err)
+ return nil, fmt.Errorf("failed to combine nonces for payload signing: %w", 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.
| // Sign signs a byte payload with the provided nonces. | |
| // The return are a "partial signature". | |
| func (s *Ted25519SignerSoft) Sign(nonces []types.Nonce, payload []byte) ([]byte, error) { | |
| // sum the nonces to get the ephemeral public key and share | |
| nonceShare, noncePub, err := sumNonces(nonces) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to combine nonces: %w", err) | |
| } | |
| sig := tsed25519.SignWithShare( | |
| payload, s.privateKeyShard, nonceShare, s.pubKey, noncePub) | |
| return append(noncePub, sig...), nil | |
| // Sign signs a byte payload with the provided nonces. | |
| // The return are a "partial signature". | |
| func (s *Ted25519SignerSoft) Sign(nonces []types.Nonce, payload []byte) ([]byte, error) { | |
| // sum the nonces to get the ephemeral public key and share | |
| nonceShare, noncePub, err := sumNonces(nonces) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to combine nonces for payload signing: %w", err) | |
| } | |
| sig := tsed25519.SignWithShare( | |
| payload, s.privateKeyShard, nonceShare, s.pubKey, noncePub) | |
| return append(noncePub, sig...), nil |
| cs, ok := pv.chainSignState.Load(chainID) // | ||
| if !ok { | ||
| panic(fmt.Errorf("failed to load chain state for %s", chainID)) | ||
| } | ||
|
|
||
| css, ok := cs.(ChainSignState) | ||
| if !ok { | ||
| panic(fmt.Errorf("expected: (ChainSignState), actual: (%T)", cs)) | ||
| panic(fmt.Errorf("expected: type (ChainSignState), actual type is: (%T)", cs)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The mustLoadChainState function uses a type assertion that could panic if the type does not match. Ensure that this function is only called with the correct type and consider adding error handling instead of panicking.
signer/threshold_validator.go
Outdated
| // More or less everything belov here shoud be moved to a "cosigners" | ||
| // package. This is the actual MPC. | ||
| // MPC.SignBlock() is the actual function that does the MPC. | ||
| numPeers := len(pv.peerCosigners) | ||
| total := uint8(numPeers + 1) | ||
|
|
||
| peerStartTime := time.Now() | ||
|
|
||
| cosignersOrderedByFastest := pv.cosignerHealth.GetFastest() | ||
| cosignersForThisBlock := make([]Cosigner, pv.threshold) | ||
| cosignersForThisBlock[0] = pv.myCosigner | ||
| cosignersForThisBlock := make([]ICosigner, pv.threshold) | ||
| cosignersForThisBlock[0] = pv.MyCosigner |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The Sign function includes a comment about moving the logic to a "cosigners" package. This indicates a potential future refactor and should be tracked as a TODO item.
| // CombineSignatures combines partial signatures into a full signature | ||
| func (s *Ted25519SignerSoft) CombineSignatures(signatures []types.PartialSignature) ([]byte, error) { | ||
| sigIds := make([]int, len(signatures)) | ||
| shareSigs := make([][]byte, len(signatures)) | ||
| var ephPub []byte | ||
|
|
||
| for i, sig := range signatures { | ||
| sigIds[i] = sig.Index | ||
| if i == 0 { | ||
| ephPub = sig.Signature[:32] | ||
| } else if !bytes.Equal(sig.Signature[:32], ephPub) { | ||
| return nil, fmt.Errorf("ephemeral public keys do not match") | ||
| } | ||
| shareSigs[i] = sig.Signature[32:] | ||
| } | ||
| combinedSig := tsed25519.CombineShares(s.total, sigIds, shareSigs) | ||
|
|
||
| return append(ephPub, combinedSig...), nil | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The CombineSignatures method should validate the length of signatures before proceeding to combine them to prevent potential panics if signatures is empty.
+ if len(signatures) == 0 {
+ return nil, errors.New("no signatures provided for combination")
+ }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.
| // CombineSignatures combines partial signatures into a full signature | |
| func (s *Ted25519SignerSoft) CombineSignatures(signatures []types.PartialSignature) ([]byte, error) { | |
| sigIds := make([]int, len(signatures)) | |
| shareSigs := make([][]byte, len(signatures)) | |
| var ephPub []byte | |
| for i, sig := range signatures { | |
| sigIds[i] = sig.Index | |
| if i == 0 { | |
| ephPub = sig.Signature[:32] | |
| } else if !bytes.Equal(sig.Signature[:32], ephPub) { | |
| return nil, fmt.Errorf("ephemeral public keys do not match") | |
| } | |
| shareSigs[i] = sig.Signature[32:] | |
| } | |
| combinedSig := tsed25519.CombineShares(s.total, sigIds, shareSigs) | |
| return append(ephPub, combinedSig...), nil | |
| } | |
| // CombineSignatures combines partial signatures into a full signature | |
| func (s *Ted25519SignerSoft) CombineSignatures(signatures []types.PartialSignature) ([]byte, error) { | |
| if len(signatures) == 0 { | |
| return nil, errors.New("no signatures provided for combination") | |
| } | |
| sigIds := make([]int, len(signatures)) | |
| shareSigs := make([][]byte, len(signatures)) | |
| var ephPub []byte | |
| for i, sig := range signatures { | |
| sigIds[i] = sig.Index | |
| if i == 0 { | |
| ephPub = sig.Signature[:32] | |
| } else if !bytes.Equal(sig.Signature[:32], ephPub) { | |
| return nil, fmt.Errorf("ephemeral public keys do not match") | |
| } | |
| shareSigs[i] = sig.Signature[32:] | |
| } | |
| combinedSig := tsed25519.CombineShares(s.total, sigIds, shareSigs) | |
| return append(ephPub, combinedSig...), nil | |
| } |
| // TODO: Rename to fetchChainState | ||
| func (cosigner *LocalCosigner) getChainState(chainID string) (*ChainState, error) { | ||
| cs, ok := cosigner.chainState.Load(chainID) | ||
| if !ok { | ||
| return nil, fmt.Errorf("failed to load chain state for %s", chainID) | ||
| } | ||
|
|
||
| // Asserting cs (type any) is actually of type *ChainState | ||
| ccs, ok := cs.(*ChainState) | ||
| if !ok { | ||
| return nil, fmt.Errorf("expected: (*ChainState), actual: (%T)", cs) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The method getChainState has been updated with a TODO comment suggesting a rename. Ensure that the rename is considered and tracked appropriately.
| // Implements Cosigner interface Should not be part of Cosigner. | ||
| // Should be part of a higher level interface. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The VerifySignature method has comments suggesting it should not be part of the Cosigner interface and should be part of a higher-level interface. This indicates a potential architectural change that should be tracked and addressed.
| func (cosigner *LocalCosigner) sign(req SignatureRequest) (SignatureResponse, error) { | ||
| chainID := req.ChainID | ||
|
|
||
| res := CosignerSignResponse{} | ||
| res := SignatureResponse{} | ||
|
|
||
| ccs, err := cosigner.getChainState(chainID) | ||
| if err != nil { | ||
| return res, err | ||
| } | ||
|
|
||
| // This function has multiple exit points. Only start time can be guaranteed | ||
| metricsTimeKeeper.SetPreviousLocalSignStart(time.Now()) | ||
| metrics.MetricsTimeKeeper.SetPreviousLocalSignStart(time.Now()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The absence of output from the ast-grep command suggests that there is no call to MetricsTimeKeeper.SetPreviousLocalSignFinish within the sign method in server.go. This could indicate an inconsistency in metric tracking, as we would expect to see a corresponding finish time metric to match the start time metric that was set.
Given this information, it appears there may be an issue with the metric tracking within the sign method, as it does not follow the same pattern as other parts of the codebase where both a start and finish time are recorded.
- The
signmethod sets a start time metric (SetPreviousLocalSignStart), but there is no evidence of a corresponding finish time metric (SetPreviousLocalSignFinish) within the same method.
Analysis chain
The sign method has been updated with new logic and metric tracking. Ensure that the new logic is correct and that metric tracking is consistent with the rest of the codebase.
Based on the output, the MetricsTimeKeeper is used in various parts of the codebase to track different metrics related to signing operations. The sign method in server.go uses MetricsTimeKeeper.SetPreviousLocalSignStart to record the start time of the local sign operation. To ensure consistency, we should check if there is a corresponding SetPreviousLocalSignFinish call within the sign method to mark the end of the operation.
Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Verify that metric tracking in the sign method is consistent with the rest of the codebase.
rg 'MetricsTimeKeeper' --type go
Length of output: 636
Script:
#!/bin/bash
# Check for the corresponding SetPreviousLocalSignFinish call within the sign method in server.go
ast-grep --lang go --pattern $'func (cosigner *LocalCosigner) sign($_) ($_,$_){
$$$
MetricsTimeKeeper.SetPreviousLocalSignFinish($_)
$$$
}'
Length of output: 146
|
|
||
| // Note - Function may return before this line so elapsed time for Finish may be multiple block times | ||
| metricsTimeKeeper.SetPreviousLocalSignFinish(time.Now()) | ||
| metrics.MetricsTimeKeeper.SetPreviousLocalSignFinish(time.Now()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The comment regarding the potential for multiple block times to elapse before the SetPreviousLocalSignFinish method is called suggests a need for careful review of the timing logic to ensure accuracy.
pkg/cosigner/server.go
Outdated
| // TODO: This should only generate nonces for the cosigners that are online | ||
| // although it might doesnt matter if we arent doing DKG | ||
| // Should call an interface: dealnonce or something | ||
| threshold := uint8(cosigner.config.Config.ThresholdModeConfig.Threshold) | ||
| nonces, err := cosigner.dealer.KeyGenerator(uint8(threshold), uint8(total)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The TODO comments suggest that the nonce generation should account for online cosigners and call an interface. Ensure that this logic is implemented or tracked for future implementation.
|
@coderabbitai review |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 20
Configuration used: CodeRabbit UI
Files ignored due to path filters (4)
signer/testdata/rsa_keys.jsonis excluded by:!**/*.jsonsrc/node/chain-1_priv_validator_state.jsonis excluded by:!**/*.jsonsrc/proto/cosigner.pb.gois excluded by:!**/*.pb.gosrc/proto/remote_signer.pb.gois excluded by:!**/*.pb.go
Files selected for processing (63)
- .golangci.yml (1 hunks)
- cmd/horcrux/cmd/address.go (5 hunks)
- cmd/horcrux/cmd/config.go (6 hunks)
- cmd/horcrux/cmd/leader_election.go (2 hunks)
- cmd/horcrux/cmd/migrate.go (6 hunks)
- cmd/horcrux/cmd/root.go (2 hunks)
- cmd/horcrux/cmd/services.go (3 hunks)
- cmd/horcrux/cmd/services_test.go (9 hunks)
- cmd/horcrux/cmd/shards.go (7 hunks)
- cmd/horcrux/cmd/single_signer.go (3 hunks)
- cmd/horcrux/cmd/start.go (5 hunks)
- cmd/horcrux/cmd/state.go (3 hunks)
- cmd/horcrux/cmd/state_test.go (1 hunks)
- cmd/horcrux/cmd/threshold.go (3 hunks)
- docs/migrating.md (1 hunks)
- src/cond/cond_test.go (1 hunks)
- src/config/config.go (3 hunks)
- src/config/config_test.go (27 hunks)
- src/connector/iprivvalidator.go (1 hunks)
- src/connector/sentry_signer.go (12 hunks)
- src/connector/sentry_signer_grpc_server.go (1 hunks)
- src/cosigner/client.go (6 hunks)
- src/cosigner/icosigner_go.txt (1 hunks)
- src/cosigner/icosigner_security.go (2 hunks)
- src/cosigner/ithresholdsigner.go (1 hunks)
- src/cosigner/nodesecurity/cosigner_key_shares.go (2 hunks)
- src/cosigner/nodesecurity/cosigner_security_ecies.go (4 hunks)
- src/cosigner/nodesecurity/cosigner_security_ecies_test.go (6 hunks)
- src/cosigner/nodesecurity/cosigner_security_rsa.go (4 hunks)
- src/cosigner/nodesecurity/cosigner_security_rsa_test.go (4 hunks)
- src/cosigner/server.go (23 hunks)
- src/cosigner/server_test.go (10 hunks)
- src/cosigner/types.go (1 hunks)
- src/metrics/metrics.go (4 hunks)
- src/multiresolver/multi_test.go (3 hunks)
- src/node/cosigner_health.go (5 hunks)
- src/node/cosigner_health_test.go (1 hunks)
- src/node/cosigner_nonce_cache.go (12 hunks)
- src/node/cosigner_nonce_cache_test_go.txt (1 hunks)
- src/node/file.go (3 hunks)
- src/node/icosigner.go (1 hunks)
- src/node/ileader.go (1 hunks)
- src/node/leader_mock_test.go (1 hunks)
- src/node/node_grpc_server.go (6 hunks)
- src/node/raft_events.go (2 hunks)
- src/node/raft_store.go (6 hunks)
- src/node/raft_store_test.go (2 hunks)
- src/node/single_signer_validator.go (4 hunks)
- src/node/single_signer_validator_test.go (5 hunks)
- src/node/threshold_validator.go (30 hunks)
- src/node/threshold_validator_test.go (11 hunks)
- src/tss/doc.go (1 hunks)
- src/tss/ted25519/threshold-ed25519_signer_soft.go (1 hunks)
- src/tss/threshold_signer.go (1 hunks)
- src/tss/types.go (1 hunks)
- src/types/block.go (1 hunks)
- src/types/hrs.go (1 hunks)
- src/types/serialization.go (1 hunks)
- src/types/sign_state.go (11 hunks)
- test/horcrux_test.go (13 hunks)
- test/validator.go (3 hunks)
- test/validator_single.go (5 hunks)
- test/validator_threshold.go (7 hunks)
Files skipped from review due to trivial changes (4)
- src/cond/cond_test.go
- src/config/config_test.go
- src/node/ileader.go
- src/node/single_signer_validator_test.go
Additional comments: 103
src/connector/iprivvalidator.go (1)
- 10-16: The
IPrivValidatorinterface definition looks good and follows best practices for interface design in Go.src/cosigner/icosigner_security.go (1)
- 1-7: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [4-13]
The renaming of
CosignerSecuritytoICosignerSecurityand the update to theEncryptAndSignmethod's return type align with Go's interface naming conventions and improve clarity.src/cosigner/ithresholdsigner.go (1)
- 5-25: The
IThresholdSigner,IThresholdDealer, andIThresholdinterfaces are well-defined, with clear responsibilities and method signatures that align with their intended functionality.src/node/leader_mock_test.go (1)
- 13-41: The
MockLeaderandMockThresholdValidatorstructs, along with their methods, are correctly implemented for testing purposes, following best practices for mock object design in unit tests.src/node/raft_events.go (1)
- 1-9: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-43]
The changes to the
raft_events.gofile, including the package move and the update to thehandleLSSEventfunction, are correctly implemented and align with the summary provided.cmd/horcrux/cmd/single_signer.go (1)
- 4-10: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-37]
The updates to the
single_signer.gofile, including the change in import path and the modification to theNewSingleSignerValidatorfunction, are correctly implemented and align with the summary provided.src/types/serialization.go (1)
- 28-43: The modification of the
UnpackHRSTfunction to return anHRSTtype is correctly implemented, improving the clarity and correctness of the function's return type.src/tss/doc.go (1)
- 1-43: The documentation in
doc.gowithin thetsspackage is well-written, providing a clear overview of the package's functionality and usage.src/node/icosigner.go (1)
- 11-51: The
iMPC,ICosigner, andICosignersinterfaces, along with their methods, are well-defined, with clear responsibilities and method signatures that align with their intended functionality.src/types/hrs.go (1)
- 7-70: The
HRSandHRSTstructs, along with their methods, are correctly implemented, following best practices for struct design in Go and providing clear and concise functionality.src/node/cosigner_health_test.go (1)
- 1-76: The
MockLeaderandMockThresholdValidatorstructs, along with theTestCosignerHealthfunction, are correctly implemented for testing the cosigner health functionality, following best practices for unit testing.cmd/horcrux/cmd/state_test.go (1)
- 7-13: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-76]
The update to the import path for the
typespackage in thestate_test.gofile is correctly implemented, aligning with the summary provided.src/node/cosigner_health.go (1)
- 80-98: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-95]
The changes in the
cosigner_health.gofile, including the renaming and refactoring of types and methods, are correctly implemented and align with the summary provided.cmd/horcrux/cmd/start.go (1)
- 44-59: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-81]
The updates to the
startCmdfunction, including the inclusion of new imports and the replacement of thesignerpackage with theconnectorpackage, are correctly implemented and align with the summary provided.src/cosigner/nodesecurity/cosigner_key_shares.go (1)
- 1-11: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-102]
The changes in the
cosigner_key_shares.gofile, including the package rename and the removal of several functions, are correctly implemented and align with the summary provided.cmd/horcrux/cmd/root.go (1)
- 8-18: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-77]
The updates to the
root.gofile, including the replacement of thesignerimport withcconfigand the update to references toRuntimeConfig, are correctly implemented and align with the summary provided.src/node/raft_store_test.go (1)
- 32-67: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-102]
The changes in the
raft_store_test.gofile, including the package declaration update and the use of thenode.NewRaftStoreconstructor, are correctly implemented and align with the summary provided.src/cosigner/nodesecurity/cosigner_security_rsa_test.go (1)
- 1-22: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-80]
The changes in the
cosigner_security_rsa_test.gofile, including the package declaration update and the modifications to the test functions, are correctly implemented and align with the summary provided.src/multiresolver/multi_test.go (1)
- 10-18: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-102]
The changes in the
multi_test.gofile, including the package imports and function calls, are correctly implemented and align with the summary provided.cmd/horcrux/cmd/address.go (1)
- 46-58: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-90]
The updates to the
address.gofile, including the replacement of thesignerpackage withcconfigandtss, and the updated usage of types and functions from these packages, are correctly implemented and align with the summary provided.src/cosigner/icosigner_go.txt (1)
- 1-103: The
icosigner_go.txtfile provides a clear and informative overview of thecosignerpackage and its components, including the roles ofLocalCosignerandRemoteCosigner. This documentation enhances understanding of the package's structure and functionality.src/node/single_signer_validator.go (4)
- 10-10: The import path has been updated to use the
configpackage, aligning with the refactor's goal to improve code modularity.- 18-18: The
configfield type inSingleSignerValidatorstruct has been updated to*config.RuntimeConfig, reflecting the new package structure.- 34-34: The
NewSingleSignerValidatorfunction now correctly accepts a pointer toconfig.RuntimeConfig, ensuring compatibility with the updated package structure.- 84-84: The function
LoadPVFileis correctly used instead of the previously mentionedLoadFilePV, aligning with the changes mentioned in the PR summary.src/tss/types.go (4)
- 67-87: The
MarshalJSONmethod forEd25519Keycorrectly handles the conversion of the public key to protobuf format before marshaling. This ensures compatibility with protobuf encoding.- 89-131: The
UnmarshalJSONmethod forEd25519Keyincludes a fallback mechanism for amino unmarshaling if protobuf unmarshaling fails. This ensures backward compatibility with older key formats.- 133-143: The
ReadCometBFTPrivValidatorFilefunction correctly reads and unmarshals a CometBFT private validator key file, ensuring compatibility with CometBFT's key storage format.- 145-159: The
WriteToFilegeneric function is correctly implemented to marshal and write any private key type that satisfies theVaultPrivateKeyinterface to a file, with appropriate file permissions for security.src/tss/ted25519/threshold-ed25519_signer_soft.go (5)
- 47-68: The
Ted25519SignerSoftstruct and its constructor functionNewTed25519SignerSoftare correctly implemented to initialize a threshold signer with the necessary parameters.- 74-86: The
Signfunction inTed25519SignerSoftcorrectly implements threshold signing by summing the nonces and using the threshold-ed25519 library to sign the payload.- 88-112: The
sumNoncesfunction correctly sums the nonces and checks the bounds of the ephemeral share to ensure it is within valid bounds for theSignWithSharefunction.- 114-137: The
NonceGeneratorstruct and itsGenerateNoncesmethod are correctly implemented to generate nonces for use in multi-party computation (MPC) signature schemes.- 139-157: The
CombineSignaturesfunction inTed25519SignerSoftcorrectly combines partial signatures into a full signature, ensuring the correct assembly of the final signature from shard signatures.cmd/horcrux/cmd/config.go (3)
- 5-11: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [8-17]
The import statement correctly replaces references from the
signerpackage to thecconfigpackage, aligning with the reorganization of the codebase.
- 70-90: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [51-163]
The
initCmdfunction correctly updates references from thesignerpackage to thecconfigpackage, including changes to function calls, variable types, and constants related to the signer configuration.
- 137-140: The flag definition for
flagSignModecorrectly uses thecconfig.SignModeThresholdconstant, reflecting the updated package references.cmd/horcrux/cmd/leader_election.go (2)
- 8-14: The import statements correctly update the package paths for
nodesecurity,multiresolver, andprototo reflect their new locations under thesrcdirectory.- 120-127: In the
getLeaderCmdfunction, references to loading cosigner RSA keys are correctly updated to use thenodesecuritypackage, aligning with the restructured package organization.cmd/horcrux/cmd/services_test.go (4)
- 1-1: The package name change from
signer_testtocmd_testcorrectly reflects the file's location within thecmdpackage structure.- 73-79: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [76-85]
The
TestIsNotRunningfunction correctly uses thecmd.RequireNotRunningfunction, demonstrating proper usage of the updated package references.
- 169-175: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [139-172]
The
TestConcurrentStartfunction correctly tests the concurrent execution and graceful termination of services, ensuring that the PID file exists after concurrent attempts.
- 188-194: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [191-216]
The
TestIsRunningAndWaitForServicefunction correctly simulates a running service and tests the behavior of waiting for the service to terminate and handling PID file checks.src/cosigner/nodesecurity/cosigner_security_rsa.go (3)
- 18-18: The implementation of
CosignerSecurityRSAcorrectly adheres to thecosigner.ICosignerSecurityinterface, ensuring compatibility with the expected security operations.- 132-132: The
EncryptAndSignmethod inCosignerSecurityRSAcorrectly implements the encryption and signing of data, ensuring secure communication between cosigners.- 198-198: The
DecryptAndVerifymethod inCosignerSecurityRSAcorrectly implements the decryption of data and verification of its signature, ensuring the authenticity of the sender.src/cosigner/server_test.go (3)
- 1-1: The package name change to
cosigner_testand updates to imports correctly reflect the file's purpose and location within thecosignerpackage structure.- 105-136: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [47-164]
The test functions for RSA and ECIES-based local cosigner signing correctly implement the testing of threshold signing with various configurations, ensuring the functionality works as expected.
- 143-179: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [108-231]
The
testLocalCosignerSignhelper function correctly sets up and tests the local cosigner signing process, ensuring that threshold signing works as expected with both RSA and ECIES configurations.src/cosigner/nodesecurity/cosigner_security_ecies.go (3)
- 19-19: The implementation of
CosignerSecurityECIEScorrectly adheres to thecosigner.ICosignerSecurityinterface, ensuring compatibility with the expected security operations for ECIES encryption and ECDSA signing.- 140-140: The
EncryptAndSignmethod inCosignerSecurityECIEScorrectly implements the encryption and signing of data using ECIES and ECDSA, ensuring secure communication between cosigners.- 211-211: The
DecryptAndVerifymethod inCosignerSecurityECIEScorrectly implements the decryption of ECIES-encrypted data and verification of its ECDSA signature, ensuring the authenticity of the sender.src/connector/sentry_signer_grpc_server.go (7)
- 21-21: The implementation of
proto.RemoteSignerServeris correctly declared forSentrySignerGRPCServer.- 23-25: The comment provides a clear explanation of the
SentrySignerGRPCServer's role in the system.- 37-48: The constructor function
NewSentrySignerGRPCServeris correctly implemented and initializes all necessary fields ofSentrySignerGRPCServer.- 51-60: The
OnStartmethod correctly sets up the GRPC server and registers theSentrySignerGRPCServeras aRemoteSignerServer. Proper error handling is implemented for thenet.Listencall.- 63-65: The
OnStopmethod correctly performs a graceful stop of the GRPC server.- 87-102: The
Signmethod correctly processes sign block requests, including error handling and metric tracking. The use ofsignAndTrackfor signing and metric tracking is a good practice.- 104-193: The
signAndTrackfunction is well-implemented, with comprehensive error handling and metric tracking for different signing steps and outcomes. The separation of concerns and clear logic flow enhance readability and maintainability.test/validator.go (2)
- 17-17: The import path for the
protopackage has been updated.- 192-192: The comment in the
enablePrivvalListenerfunction has been updated.src/node/file.go (3)
- 1-1: The package has been renamed from "signer" to "node".
- 10-10: The import path for types has been updated to reflect the new package structure.
- 156-156: The function
LoadFilePVhas been renamed toLoadPVFile.src/node/cosigner_nonce_cache.go (4)
- 1-1: The package has been renamed from "signer" to "node".
- 7-7: Usage of atomic operations for
lastReconcileNoncessuggests attention to thread safety.- 147-148: The replacement of "Cosigner" type with "ICosigner" indicates an interface abstraction, likely for better modularity.
- 296-304: The update in metrics usage aligns with the new package structure and naming conventions.
src/metrics/metrics.go (3)
- 1-1: The package has been renamed to "metrics", aligning with its functionality.
- 17-27: Introduction of new error types like
BeyondBlockErrorandSameBlockErrorenhances error handling specificity.- 98-329: The renaming and reorganization of Prometheus metrics to reflect the new package name and structure is a good practice for maintainability and clarity.
src/node/raft_store.go (5)
- 8-8: The package has been correctly renamed from
signertonodeto reflect its functionality more accurately.- 22-24: Import paths for
cosignerandtypespackages have been updated to reflect the new package structure. Ensure that these new paths are correct and accessible within the project structure.Verification successful
The verification process has confirmed the existence of directories named
cosignerandtypeswithin thesrcdirectory of the project. This aligns with the updated import paths mentioned in the review comment, indicating that the paths are correct and accessible within the project structure.* 72-80: The `NewRaftStore` function signature has been modified to accept `cosigner *cosigner.LocalCosigner` and `cosigners []ICosigner` parameters. This change aligns with the refactor to use more specific types for cosigners. Ensure all calls to this function have been updated accordingly.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify the new import paths are correct and accessible fd "cosigner" | xargs -I {} test -f {} || echo "cosigner path not found" fd "types" | xargs -I {} test -f {} || echo "types path not found"Length of output: 268
Script:
#!/bin/bash # Verify the new import paths are correct and accessible by checking for directories fd --type d "cosigner" || echo "cosigner directory not found" fd --type d "types" || echo "types directory not found"Length of output: 67
Verification successful
Given the absence of output from the
ast-grepcommand searching for calls toNewRaftStorewith the old parameter list, it suggests that there are no instances in the codebase whereNewRaftStoreis called without the new parameterscosigner *cosigner.LocalCosignerandcosigners []ICosigner. This implies that all calls toNewRaftStorehave likely been updated to include these new parameters, aligning with the refactor mentioned in the review comment.* 90-90: Setting `thresholdValidator.MyCosigner` in the `SetThresholdValidator` function is a good practice as it ensures that the `ThresholdValidator` has a reference to its associated cosigner. This change enhances clarity and maintainability. * 112-112: The commented-out line related to registering the `CosignerServer` with the `grpcServer` and the subsequent change to the registration call reflect an adjustment in the server's setup. This change likely aligns with the refactor's goals but requires verification that the new setup works as intended and that no functionality is lost.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for old `NewRaftStore` calls without the new parameters ast-grep --lang go --pattern $'NewRaftStore($_, $_, $_, $_, $_)'Length of output: 65
test/validator_threshold.go (4)
- 15-17: The imports have been modified to include new packages such as
config,cosigner/nodesecurity, andtss. This change likely supports the new functionality introduced in the refactor. Ensure these packages exist and are correctly referenced.Verification successful
The verification process has confirmed the existence of directories corresponding to the new import paths
config,nodesecurity, andtsswithin the project structure. These directories are located atsrc/config/,src/cosigner/nodesecurity/, andsrc/tss/, respectively. This confirms that the imports in thevalidator_threshold.gofile are correctly referenced and accessible within the project.* 187-187: The call to `nodesecurity.CreateCosignerECIESShards` introduces a new way to create ECIES shards for cosigners. This change is part of the refactor to enhance security and modularity. Verify that this function is implemented correctly and that its output is used appropriately throughout the system.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify the new import paths are correct and accessible fd "config" | xargs -I {} test -f {} || echo "config path not found" fd "nodesecurity" | xargs -I {} test -f {} || echo "nodesecurity path not found" fd "tss" | xargs -I {} test -f {} || echo "tss path not found"Length of output: 407
Script:
#!/bin/bash # Adjusting the script to correctly verify the existence of directories for the new import paths fd -t d "config" || echo "config directory not found" fd -t d "nodesecurity" || echo "nodesecurity directory not found" fd -t d "tss" || echo "tss directory not found"Length of output: 101
Verification successful
The initial script intended to verify the implementation and usage of
CreateCosignerECIESShardsdid not produce any output. This could mean that the function is not present, not used in the expected manner, or there was an issue with the search parameters. To ensure a thorough verification, a different approach is needed to search for the function's implementation and its usage across the codebase.Given the lack of results from the
ast-grepcommand, it's prudent to use a more general search tool likerg(ripgrep) to search for the function name in the codebase. This will help in identifying both the implementation of the function and its usage in various files.
The search results confirm the implementation of
CreateCosignerECIESShardswithinsrc/cosigner/nodesecurity/cosigner_key_shares.goand its usage across multiple test files (horcrux_test.go,validator_threshold.go) and a command file (cmd/horcrux/cmd/shards.go). This indicates that the function is indeed implemented and utilized within the system as intended for enhancing security and modularity in the creation of ECIES shards for cosigners.Based on this information, the review comment regarding the verification of the implementation and usage of
CreateCosignerECIESShardsis supported by the evidence from the codebase.* 218-220: The configuration setup in the `config.Config` struct, especially the introduction of `SignMode` and `ThresholdModeConfig`, aligns with the refactor's goal to enhance modularity and clarity in configuration management. Ensure that these configurations are correctly applied and tested.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify the implementation and usage of CreateCosignerECIESShards ast-grep --lang go --pattern $'CreateCosignerECIESShards($_)'Length of output: 62
Script:
#!/bin/bash # Search for the implementation and usage of CreateCosignerECIESShards across the codebase rg "CreateCosignerECIESShards"Length of output: 654
Verification successful
The verification process has revealed that both
SignModeandThresholdModeConfigare extensively used and tested within the codebase. The presence of these configurations in various test files (config_test.go,validator_threshold.go,horcrux_test.go, etc.) and their application in the main code (e.g.,threshold_signer.go,server_test.go,config.go) indicate that the configurations have been correctly applied and tested, aligning with the refactor's goal to enhance modularity and clarity in configuration management.* 256-264: The update to `getShardedPrivvalKey` to use the `tss` package for generating threshold shards is a significant change. This update likely improves the security and efficiency of key management. Ensure that the `tss.GeneratePersistentThresholdSignShards` function is correctly implemented and that its output is properly handled.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify the correct application and testing of the new configuration setup echo "Manual testing required to verify configuration application and effectiveness."Length of output: 166
Script:
#!/bin/bash # Verify if the new configuration setup is correctly applied and tested by searching for tests related to SignMode and ThresholdModeConfig # Search for tests involving SignMode echo "Searching for tests involving SignMode..." rg "SignMode" --type-add 'go:*.go' --type 'go' # Search for tests involving ThresholdModeConfig echo "Searching for tests involving ThresholdModeConfig..." rg "ThresholdModeConfig" --type-add 'go:*.go' --type 'go'Length of output: 6311
src/node/cosigner_nonce_cache_test_go.txt (5)
- 26-57: The
TestMovingAveragefunction effectively tests the moving average calculation with various scenarios. The use ofrequire.Lenandrequire.Equalto assert conditions is appropriate. This test is well-structured and provides good coverage for the moving average functionality.- 59-120: The
TestClearNoncesfunction tests the clearing of nonces from theCosignerNonceCache. It's good to see thorough testing of the cache's behavior under different conditions. However, ensure that thegetTestLocalCosignersfunction correctly sets up the test environment and that the assertions accurately reflect the expected outcomes.- 144-191: The
TestNonceCacheDemandfunction tests the nonce cache under load, simulating demand. This test is crucial for understanding how the cache behaves under stress. Ensure that theLoadNandStartmethods are correctly implemented and that the test's assumptions about cache size and pruning behavior are valid.Verification successful
The script intended to verify the implementation of
LoadNandStartmethods within the nonce cache testing did not produce any output. This outcome suggests that either the methods do not exist, were not correctly identified by the script, or the script was not correctly formulated to capture the necessary details.Given the lack of output, it's prudent to refine the search strategy to ensure we're accurately verifying the presence and implementation of these methods. Specifically, we can adjust the script to search more broadly for the
LoadNandStartmethods within the Go files, without assuming specific argument patterns, which might have limited the search results previously.
The refined search successfully identified the implementations of both
LoadNandStartmethods within theCosignerNonceCacheclass, as well as other occurrences ofStartmethods in different contexts. This confirms that theLoadNandStartmethods are indeed implemented and utilized within the nonce cache testing, aligning with the original review comment's concerns about ensuring these methods are correctly implemented for the test's validity.Given this confirmation, the original review comment stands as valid, emphasizing the importance of these methods' correct implementation for the nonce cache's behavior under load testing.
* 193-249: The `TestNonceCacheExpiration` function tests nonce expiration logic within the cache. This test is important for ensuring that nonces are correctly expired and pruned. The setup and assertions seem appropriate, but verify that the timing and expiration logic align with the system's requirements. * 251-402: The `TestNonceCachePrune` function tests various scenarios for nonce pruning. The detailed test cases and the use of a custom `testCase` struct for organizing scenarios are commendable. Ensure that the `PruneNonces` method is correctly implemented and that all test cases accurately reflect expected behavior.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify the implementation of LoadN and Start methods in nonce cache testing ast-grep --lang go --pattern $'LoadN($_, $_)' && ast-grep --lang go --pattern $'Start($_)'Length of output: 89
Script:
#!/bin/bash # Broaden the search for LoadN and Start methods in the Go codebase ast-grep --lang go --pattern $'func ($_ *$_) LoadN($$$)' && ast-grep --lang go --pattern $'func ($_ *$_) Start($$$)'Length of output: 6672
src/cosigner/server.go (4)
- 1-1: The package has been correctly renamed to
cosignerfromsignerto reflect its functionality more accurately.- 10-15: The import paths have been updated to reflect the new package structure and dependencies. Ensure that these paths are correct and accessible in the project.
Verification successful
Given the challenges encountered with the initial verification script and the need to verify the updated import paths in the Go project, a more effective approach is required. To indirectly verify the correctness and accessibility of the import paths, we can search for Go files within the project that reference these paths. This method assumes that if the import paths are correctly referenced in the project's Go files, they are likely correct and accessible.
The verification process has successfully identified multiple Go files within the project that reference the updated import paths. This indicates that the import paths are correctly integrated into the project's structure and are being actively used across various components. Therefore, the updated import paths are verified as correct and accessible within the project's context.
* 35-49: The `LocalCosigner` struct now includes a `dealer` field of type `IThresholdDealer`, aligning with the refactor's goal to utilize interfaces for nonce generation. This change enhances modularity and flexibility in nonce generation strategies. * 221-244: > 📝 **NOTE** > This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [230-294]Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify the existence and accessibility of the updated import paths. fd --exec test -d {}Length of output: 4920
Script:
#!/bin/bash # Search for Go files that reference the updated import paths. rg --files-with-matches 'github.com/strangelove-ventures/horcrux/src/config' && \ rg --files-with-matches 'github.com/strangelove-ventures/horcrux/src/metrics' && \ rg --files-with-matches 'github.com/strangelove-ventures/horcrux/src/tss' && \ rg --files-with-matches 'github.com/strangelove-ventures/horcrux/src/tss/ted25519' && \ rg --files-with-matches 'github.com/strangelove-ventures/horcrux/src/types'Length of output: 2022
The
signmethod has been updated to accept aSignatureRequestparameter, reflecting the changes in the PR summary. The method's implementation correctly handles the new signature request, including nonce combination and signature generation. Ensure error handling is robust, especially around nonce generation and signature combination.src/node/threshold_validator_test.go (6)
- 1-26: The package has been renamed from
signertonode_test, and imports have been updated accordingly. This change aligns with the refactor's goal to improve clarity and modularity.- 49-85: Introduced a
MockValidatortype and its constructorNewMockValidator. This addition facilitates testing by mocking theThresholdValidatorbehavior. Ensure that the mock implementation is used correctly in tests to simulate real scenarios accurately.- 87-104: The
TestMainfunction has been simplified to always use a new instance ofconfig.RuntimeConfig. This change removes the conditional loading of configuration from an environment variable, streamlining the test setup process.- 105-118: Test functions
TestThresholdValidator2of2,TestThresholdValidator3of3,TestThresholdValidator2of3, andTestThresholdValidator3of5have been updated to accepttestConfigas a parameter. This change ensures that tests use a consistent configuration, enhancing test reliability.- 1-131: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [122-139]
The
loadKeyForLocalCosignerfunction now accepts aconfigparameter. This modification allows the function to use dynamic configuration for key file paths, improving flexibility and maintainability.
- 407-428: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [377-440]
The
getTestLocalCosignersfunction has been updated to use theconfigpackage instead of theCosignerConfigtype directly. This change aligns with the refactor's goal to improve modularity by using more granular configurations.test/horcrux_test.go (4)
- 9-14: Imports have been updated to reflect the new package structure and types, including the addition of
configandtsspackages. This change supports the refactor's goal to improve modularity and clarity.- 30-84: Function comments have been updated to replace "cosigner nodes" with "cosigner cosigner", clarifying the terminology used in the context of the tests. This change improves readability and consistency in the documentation.
- 6-17: > 📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [377-440]
The code has been updated to use types from the
tssandconfigpackages, such as replacingsigner.CosignerEd25519Keywithtss.Ed25519Key. These changes align with the refactor's goal to improve modularity by using more granular and specific types.
- 27-87: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1-660]
The test file has been thoroughly updated to align with the refactor's goals, including improved modularity, clarity, and the use of updated types and packages. Ensure that all tests are updated to reflect these changes and that they pass successfully to verify the refactor's integrity.
src/node/threshold_validator.go (4)
- 1-1: The package name change from "signer" to "node" aligns with the PR's objective to refactor and reorganize the codebase for clarity and modularity.
- 79-90: The introduction of
StillWaitingForBlockErrorandSameBlockErrortypes for error handling is a good practice. It allows for more precise error handling and improves the readability of the code by making the error conditions explicit.- 116-132: The
BeyondBlockErrortype and its usage demonstrate thoughtful error handling, particularly in the context of blockchain operations where the sequence and timing of blocks are critical. This addition enhances the robustness of the error handling mechanism.- 352-352: The
GetPubKeymethod correctly implements the interface requirement. Ensure that the public key retrieval logic is robust and handles any potential errors from theMyCosigner.GetPubKeycall.
| validator IPrivValidator | ||
| logger cometlog.Logger | ||
| listenAddr string |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The validator field should be documented to explain its role and the expected interface it implements.
Consider adding a comment above the validator field to explain its purpose and the interface it implements for clarity.
| func (s *SentrySignerGRPCServer) PubKey(ctx context.Context, req *proto.PubKeyRequest) (*proto.PubKeyResponse, error) { | ||
| chainID := req.ChainId | ||
|
|
||
| metrics.TotalPubKeyRequests.WithLabelValues(chainID).Inc() | ||
|
|
||
| pubKey, err := s.validator.GetPubKey(ctx, chainID) | ||
| if err != nil { | ||
| s.logger.Error( | ||
| "Failed to get Pub Key", | ||
| "chain_id", chainID, | ||
| "error", err, | ||
| ) | ||
| return nil, err | ||
| } | ||
|
|
||
| return &proto.PubKeyResponse{ | ||
| PubKey: pubKey, | ||
| }, nil | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The PubKey method correctly handles the public key request, including error logging and metric incrementation. However, consider adding error handling for potential failures in metric updates.
While the method correctly handles the main logic, adding defensive programming practices around metric updates could prevent potential issues in metric reporting.
|
|
||
| cosigners[i] = cosigner | ||
|
|
||
| err = loadKeyForLocalCosigner(cosigner, privateKey.PubKey(), testChainID, privShards[i]) | ||
| err = loadKeyForLocalCosigner(cosigner, privateKey.PubKey(), testChainID, privShards[i], cosignerConfig) | ||
| require.NoError(t, err) | ||
|
|
||
| err = loadKeyForLocalCosigner(cosigner, privateKey.PubKey(), testChainID2, privShards[i]) | ||
| err = loadKeyForLocalCosigner(cosigner, privateKey.PubKey(), testChainID2, privShards[i], cosignerConfig) | ||
| require.NoError(t, err) | ||
| } | ||
|
|
||
| return cosigners, privateKey.PubKey() | ||
| } | ||
|
|
||
| /* | ||
| func testThresholdValidatorLeaderElection(t *testing.T, threshold, total uint8) { | ||
| cosigners, pubKey := getTestLocalCosigners(t, threshold, total) | ||
| peers, pubKey := getTestLocalCosigners(t, threshold, total) | ||
| thresholdValidators := make([]*ThresholdValidator, 0, total) | ||
| var leader *ThresholdValidator | ||
| thresholdValidators := make([]*MockThresholdValidator, 0, total) | ||
| var leader *signer.ThresholdValidator | ||
| leaders := make([]*MockLeader, total) | ||
| ctx := context.Background() | ||
| for i, cosigner := range cosigners { | ||
| peers := make([]Cosigner, 0, len(cosigners)-1) | ||
| for j, otherCosigner := range cosigners { | ||
| for i, peer := range peers { | ||
| peers := make([]signer.ICosigner, 0, len(peers)-1) | ||
| for j, otherCosigner := range peers { | ||
| if i != j { | ||
| peers = append(peers, otherCosigner) | ||
| } | ||
| } | ||
| leaders[i] = &MockLeader{id: cosigner.GetIndex(), leader: leader} | ||
| tv := NewThresholdValidator( | ||
| leaders[i] = &MockLeader{id: peer.GetIndex(), leader: leader} | ||
| tv := NewMockValidator( | ||
| cometlog.NewNopLogger(), | ||
| cosigner.config, | ||
| peer.config, | ||
| int(threshold), | ||
| time.Second, | ||
| 1, | ||
| cosigner, | ||
| peer, | ||
| peers, | ||
| leaders[i], | ||
| ) | ||
| if i == 0 { | ||
| leader = tv | ||
| leaders[i].leader = tv | ||
| leader = tv.ThresholdValidator | ||
| leaders[i].leader = tv.ThresholdValidator | ||
| } | ||
| thresholdValidators = append(thresholdValidators, tv) | ||
| thresholdValidators = append(thresholdValidators, tv.ThresholdValidator) | ||
| defer tv.Stop() | ||
| err := tv.LoadSignStateIfNecessary(testChainID) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [447-660]
The testThresholdValidatorLeaderElection function has been commented out. If this function is no longer relevant or has been replaced by another test, consider removing it entirely to keep the codebase clean and maintainable.
Consider removing the commented-out testThresholdValidatorLeaderElection function if it's no longer needed, to maintain code cleanliness.
| // TODO: Must be a better way to do this? | ||
| type nodecacheconfigs struct { | ||
| defaultGetNoncesInterval time.Duration | ||
| defaultGetNoncesTimeout time.Duration | ||
| defaultNonceExpiration time.Duration | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The nodecacheconfigs struct and its fields are introduced to configure nonce handling. Ensure these configurations are used consistently across the codebase and consider making these configurations more accessible or modifiable through external configuration files or environment variables for greater flexibility.
type nodecacheconfigs struct {
defaultGetNoncesInterval time.Duration
defaultGetNoncesTimeout time.Duration
defaultNonceExpiration time.Duration
}| package node | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "os" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/strangelove-ventures/horcrux/pkg/types" | ||
| "github.com/strangelove-ventures/horcrux/src/cosigner" | ||
|
|
||
| "github.com/strangelove-ventures/horcrux/src/config" | ||
| "github.com/strangelove-ventures/horcrux/src/metrics" | ||
|
|
||
| "github.com/strangelove-ventures/horcrux/src/types" | ||
|
|
||
| "github.com/cometbft/cometbft/libs/log" | ||
| cometrpcjsontypes "github.com/cometbft/cometbft/rpc/jsonrpc/types" | ||
| "github.com/google/uuid" | ||
| "github.com/strangelove-ventures/horcrux/signer/proto" | ||
| "golang.org/x/sync/errgroup" | ||
| "google.golang.org/grpc/codes" | ||
| "google.golang.org/grpc/status" | ||
| ) | ||
|
|
||
| var _ PrivValidator = &ThresholdValidator{} | ||
| // TODO: Must be a better way to do this? | ||
| type nodecacheconfigs struct { | ||
| defaultGetNoncesInterval time.Duration | ||
| defaultGetNoncesTimeout time.Duration | ||
| defaultNonceExpiration time.Duration | ||
| } | ||
|
|
||
| func nodecacheconfig() nodecacheconfigs { | ||
| return nodecacheconfigs{ | ||
| defaultGetNoncesInterval: config.DefaultGetNoncesInterval, | ||
| defaultGetNoncesTimeout: config.DefaultGetNoncesTimeout, | ||
| defaultNonceExpiration: config.DefaultNonceExpiration, | ||
| } | ||
| } | ||
|
|
||
| // ThresholdValidator is the server that responds to sign requests from the "sentry" | ||
| // Implements the [connector.IPrivValidator] interface. | ||
| /* | ||
| TODO: Move some parts of this to the MPC | ||
| */ | ||
| type ThresholdValidator struct { | ||
| config *RuntimeConfig | ||
| config *config.RuntimeConfig | ||
|
|
||
| threshold int | ||
|
|
||
| grpcTimeout time.Duration | ||
|
|
||
| chainState sync.Map | ||
| grpcTimeout time.Duration // TODO ask if this should move to icosigner? | ||
|
|
||
| // chainSignState is the watermark for sent blocks we have started to process | ||
| chainSignState sync.Map // - chainSignState["chainid"] -> types.chainSignState | ||
| // MPC *MPC // This is our multi party computation/communucatibn | ||
| // our own cosigner | ||
| myCosigner *LocalCosigner | ||
| MyCosigner *cosigner.LocalCosigner // TODO Should be an interface as well. | ||
|
|
||
| // peer cosigners | ||
| peerCosigners Cosigners | ||
| peerCosigners ICosigners // "i.e clients to call" | ||
|
|
||
| leader Leader | ||
| leader ILeader | ||
|
|
||
| logger log.Logger | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [43-75]
The ThresholdValidator struct has been significantly modified. It's crucial to ensure that all new fields are properly initialized and used throughout the codebase. Additionally, the TODO comments suggest areas for future improvement, such as abstracting the MyCosigner field to an interface and considering the placement of grpcTimeout. Addressing these TODOs can enhance the code's modularity and maintainability.
| // although it might doesnt matter if we arent doing DKG | ||
| // Should call an interface: dealnonce or something | ||
| threshold := uint8(cosigner.config.Config.ThresholdModeConfig.Threshold) | ||
| nonces, err := cosigner.dealer.GenerateNonces(uint8(threshold), uint8(total)) | ||
| if err != nil { | ||
| fmt.Println("Error is: ", err) | ||
| return nil, err |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The generateNonces method correctly uses the dealer interface for nonce generation, aligning with the refactor's objectives to improve modularity. However, the error logging with fmt.Println("Error is: ", err) is not ideal for production code. Consider using a structured logging approach for better error visibility and management.
- fmt.Println("Error is: ", err)
+ logger.Error("Error generating nonces", "error", 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.
| // TODO: This should only generate nonces for the cosigners that are online | |
| // although it might doesnt matter if we arent doing DKG | |
| // Should call an interface: dealnonce or something | |
| threshold := uint8(cosigner.config.Config.ThresholdModeConfig.Threshold) | |
| nonces, err := cosigner.dealer.GenerateNonces(uint8(threshold), uint8(total)) | |
| if err != nil { | |
| fmt.Println("Error is: ", err) | |
| // TODO: This should only generate nonces for the cosigners that are online | |
| // although it might doesnt matter if we arent doing DKG | |
| // Should call an interface: dealnonce or something | |
| threshold := uint8(cosigner.config.Config.ThresholdModeConfig.Threshold) | |
| nonces, err := cosigner.dealer.GenerateNonces(uint8(threshold), uint8(total)) | |
| if err != nil { | |
| logger.Error("Error generating nonces", "error", err) |
| // Ed25519Key is a single Ed255219 key shard for an m-of-n threshold signer. | ||
| // TODO: This should be renamed to SignerEd25519 and tbh Private shard should private. | ||
| type PersistentEd25519Key struct { | ||
| pubKey PubKey // Public key of the persistent shard. Pubkey is the same for all shards. | ||
| privateShard []byte // | ||
| index int // Shamir index of this shard | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The TODO comment on line 24 suggests renaming PersistentEd25519Key to SignerEd25519 and making the privateShard field private. This change would improve encapsulation and naming clarity.
Consider renaming PersistentEd25519Key to SignerEd25519 and making the privateShard field private to improve encapsulation and naming clarity.
| // GenerateEd25519ThresholdSignShards creates a map of shards from a private key | ||
| func GenerateEd25519ThresholdSignShards(pv []byte, threshold, shards uint8) map[uint8][]byte { | ||
| privShards := tsed25519.DealShares(tsed25519.ExpandSecret(pv[:32]), threshold, shards) | ||
| // TODO: Check that the length of privShards is equal to the number of shards | ||
| // TODO: Check that the pubkey is the same for all shards | ||
| out := make(map[uint8][]byte, shards) | ||
| for id, shard := range privShards { | ||
| id := uint8(id + 1) | ||
| out[id] = shard | ||
| } | ||
| return out |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The GenerateEd25519ThresholdSignShards function correctly generates private key shards for threshold signing using the threshold-ed25519 library. However, the TODO comments suggest adding checks for the length of privShards and the consistency of the public key across shards.
Consider implementing the checks mentioned in the TODO comments to ensure the correct number of shards and consistent public keys.
| type AssymetricKey struct { | ||
| privateKey []byte | ||
| privateShard []byte | ||
| } | ||
|
|
||
| type AssymetricKeyShard struct { | ||
| AssymetricKey | ||
| threshold uint8 | ||
| total uint8 | ||
| id uint8 // ID is the Shamir index or this shard. | ||
|
|
||
| } | ||
|
|
||
| type Ted25519SignerDealer struct { | ||
| Ted25519SignerSoft | ||
| } | ||
|
|
||
| // Ted25519SignerSoft is a threshold signer that uses the threshold-ed25519 library | ||
| // to perform the signing operations. | ||
| // Its only responsibility is to sign a payload and combine signatures | ||
| type Ted25519SignerSoft struct { | ||
| privateKeyShard []byte | ||
| pubKey []byte | ||
| threshold uint8 | ||
| total uint8 | ||
| id uint8 | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The AssymetricKey and AssymetricKeyShard structs are defined to represent asymmetric keys and their shards, including a unique ID for each shard. The naming convention for AssymetricKey should be corrected to AsymmetricKey.
Correct the spelling of AssymetricKey to AsymmetricKey to align with the correct spelling of "asymmetric."
| func TestNonceCache(_ *testing.T) { | ||
| nc := NonceCache{} | ||
| for i := 0; i < 10; i++ { | ||
| nc.Add(&CachedNonce{UUID: uuid.New(), Expiration: time.Now().Add(1 * time.Second)}) | ||
| } | ||
|
|
||
| nc.Delete(nc.Size() - 1) | ||
| nc.Delete(0) | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The test TestNonceCache correctly adds and deletes entries from the NonceCache. This test ensures basic functionality works as expected. However, it lacks assertions to verify the state of the cache after operations. Consider adding assertions to confirm the cache's size or contents after additions and deletions.
+ require.Equal(t, expectedSize, nc.Size(), "Cache size after operations does not match expected")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.
| func TestNonceCache(_ *testing.T) { | |
| nc := NonceCache{} | |
| for i := 0; i < 10; i++ { | |
| nc.Add(&CachedNonce{UUID: uuid.New(), Expiration: time.Now().Add(1 * time.Second)}) | |
| } | |
| nc.Delete(nc.Size() - 1) | |
| nc.Delete(0) | |
| } | |
| func TestNonceCache(_ *testing.T) { | |
| nc := NonceCache{} | |
| for i := 0; i < 10; i++ { | |
| nc.Add(&CachedNonce{UUID: uuid.New(), Expiration: time.Now().Add(1 * time.Second)}) | |
| } | |
| nc.Delete(nc.Size() - 1) | |
| nc.Delete(0) | |
| require.Equal(t, expectedSize, nc.Size(), "Cache size after operations does not match expected") | |
| } |
test
Summary by CodeRabbit
New Features
Refactor
Bug Fixes
Documentation
Style
Tests
Chores