From 34e08f1e41e79e8a54549bd40c3da1a76a045c9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Negovanovi=C4=87?= <93934272+Stefan-Ethernal@users.noreply.github.com> Date: Tue, 31 Oct 2023 08:28:25 +0100 Subject: [PATCH] Extract BLS library used in polybft to a standalone package (#1981) * Introduce bls package * Remove MarshalMessageToBigInt (unused) * Use bls package in polybft consensus * Adopt changes from #1973 * Remove package alias for bls package * Revert GeneratePrivateKey rename * Revive Test_MakeKOSKSignature and Test_AggregatedSign * Rebase fix * Fix TestAccount * Reorder imports --- .../signer/hash2point.go => bls/arithmetic.go | 0 .../arithmetic_test.go | 3 +- {consensus/polybft/signer => bls}/private.go | 0 .../polybft/signer => bls}/private_test.go | 0 {consensus/polybft/signer => bls}/public.go | 14 ++++ .../polybft/signer => bls}/public_test.go | 0 .../polybft/signer => bls}/signature.go | 13 +++- .../polybft/signer => bls}/signature_test.go | 55 +++++++++------- .../signer => bls}/testcases/hashToPoint.json | 0 .../polybft/signer/common.go => bls/utils.go | 42 +++++++----- bls/utils_test.go | 66 +++++++++++++++++++ command/polybftsecrets/params_test.go | 5 +- command/rootchain/deploy/deploy.go | 4 +- .../registration/register_validator.go | 7 +- consensus/polybft/checkpoint_manager.go | 2 +- consensus/polybft/checkpoint_manager_test.go | 7 +- consensus/polybft/consensus_runtime.go | 4 +- consensus/polybft/consensus_runtime_test.go | 6 +- consensus/polybft/extra.go | 2 +- consensus/polybft/extra_test.go | 47 ++++++------- consensus/polybft/fsm.go | 18 ++--- consensus/polybft/fsm_test.go | 35 +++++----- consensus/polybft/hash_test.go | 6 +- consensus/polybft/helpers_test.go | 2 +- consensus/polybft/polybft.go | 4 +- consensus/polybft/polybft_test.go | 4 +- consensus/polybft/proposer_calculator_test.go | 2 +- consensus/polybft/sc_integration_test.go | 5 +- consensus/polybft/signer/utils.go | 64 ++++++------------ consensus/polybft/signer/utils_test.go | 65 +----------------- consensus/polybft/stake_manager.go | 2 +- consensus/polybft/state_store_epoch_test.go | 2 +- consensus/polybft/state_sync_manager.go | 30 +++++---- consensus/polybft/state_sync_manager_test.go | 22 +++---- .../polybft/validator/genesis_validator.go | 2 +- consensus/polybft/validator/test_helpers.go | 2 +- .../polybft/validator/validator_metadata.go | 2 +- .../validator/validator_metadata_test.go | 2 +- .../validator/validator_set_delta_test.go | 2 +- consensus/polybft/wallet/account.go | 2 +- consensus/polybft/wallet/key.go | 9 +-- consensus/polybft/wallet/key_test.go | 13 ++-- e2e/framework/testserver.go | 4 +- .../precompiled/bls_agg_sigs_verification.go | 5 +- .../bls_agg_sigs_verification_test.go | 5 +- 45 files changed, 310 insertions(+), 276 deletions(-) rename consensus/polybft/signer/hash2point.go => bls/arithmetic.go (100%) rename consensus/polybft/signer/hash2point_test.go => bls/arithmetic_test.go (99%) rename {consensus/polybft/signer => bls}/private.go (100%) rename {consensus/polybft/signer => bls}/private_test.go (100%) rename {consensus/polybft/signer => bls}/public.go (90%) rename {consensus/polybft/signer => bls}/public_test.go (100%) rename {consensus/polybft/signer => bls}/signature.go (90%) rename {consensus/polybft/signer => bls}/signature_test.go (79%) rename {consensus/polybft/signer => bls}/testcases/hashToPoint.json (100%) rename consensus/polybft/signer/common.go => bls/utils.go (60%) create mode 100644 bls/utils_test.go diff --git a/consensus/polybft/signer/hash2point.go b/bls/arithmetic.go similarity index 100% rename from consensus/polybft/signer/hash2point.go rename to bls/arithmetic.go diff --git a/consensus/polybft/signer/hash2point_test.go b/bls/arithmetic_test.go similarity index 99% rename from consensus/polybft/signer/hash2point_test.go rename to bls/arithmetic_test.go index 41fd5c9782..e7620aa115 100644 --- a/consensus/polybft/signer/hash2point_test.go +++ b/bls/arithmetic_test.go @@ -8,8 +8,9 @@ import ( "math/big" "testing" - "github.com/0xPolygon/polygon-edge/helper/common" "github.com/stretchr/testify/require" + + "github.com/0xPolygon/polygon-edge/helper/common" ) //go:embed testcases/* diff --git a/consensus/polybft/signer/private.go b/bls/private.go similarity index 100% rename from consensus/polybft/signer/private.go rename to bls/private.go diff --git a/consensus/polybft/signer/private_test.go b/bls/private_test.go similarity index 100% rename from consensus/polybft/signer/private_test.go rename to bls/private_test.go diff --git a/consensus/polybft/signer/public.go b/bls/public.go similarity index 90% rename from consensus/polybft/signer/public.go rename to bls/public.go index 9004b8c798..d24638a7d1 100644 --- a/consensus/polybft/signer/public.go +++ b/bls/public.go @@ -2,6 +2,7 @@ package bls import ( "encoding/base64" + "errors" "fmt" "math/big" @@ -9,6 +10,15 @@ import ( bn256 "github.com/umbracle/go-eth-bn256" ) +const ( + PublicKeySize = 128 +) + +var ( + errInfinityPoint = errors.New("infinity point") + ErrInvalidPublicKeySize = fmt.Errorf("public key must be %d bytes long", PublicKeySize) +) + // PublicKey represents bls public key type PublicKey struct { g2 *bn256.G2 @@ -57,6 +67,10 @@ func (p *PublicKey) ToBigInt() [4]*big.Int { // UnmarshalPublicKey unmarshals bytes to public key func UnmarshalPublicKey(data []byte) (*PublicKey, error) { + if len(data) < PublicKeySize { + return nil, ErrInvalidPublicKeySize + } + g2 := new(bn256.G2) if _, err := g2.Unmarshal(data); err != nil { diff --git a/consensus/polybft/signer/public_test.go b/bls/public_test.go similarity index 100% rename from consensus/polybft/signer/public_test.go rename to bls/public_test.go diff --git a/consensus/polybft/signer/signature.go b/bls/signature.go similarity index 90% rename from consensus/polybft/signer/signature.go rename to bls/signature.go index 6801a70f29..50dc6297d4 100644 --- a/consensus/polybft/signer/signature.go +++ b/bls/signature.go @@ -1,13 +1,20 @@ package bls import ( - "errors" "fmt" "math/big" bn256 "github.com/umbracle/go-eth-bn256" ) +const ( + SignatureSize = 64 +) + +var ( + ErrInvalidSignatureSize = fmt.Errorf("signature must be %d bytes long", SignatureSize) +) + // Signature represents bls signature which is point on the curve type Signature struct { g1 *bn256.G1 @@ -48,8 +55,8 @@ func (s Signature) ToBigInt() ([2]*big.Int, error) { // UnmarshalSignature reads the signature from the given byte array func UnmarshalSignature(raw []byte) (*Signature, error) { - if len(raw) == 0 { - return nil, errors.New("cannot unmarshal signature from empty slice") + if len(raw) < SignatureSize { + return nil, ErrInvalidSignatureSize } g1 := new(bn256.G1) diff --git a/consensus/polybft/signer/signature_test.go b/bls/signature_test.go similarity index 79% rename from consensus/polybft/signer/signature_test.go rename to bls/signature_test.go index ef2b62831e..253c1203dc 100644 --- a/consensus/polybft/signer/signature_test.go +++ b/bls/signature_test.go @@ -9,6 +9,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" bn256 "github.com/umbracle/go-eth-bn256" + + "github.com/0xPolygon/polygon-edge/crypto" ) const ( @@ -16,18 +18,23 @@ const ( participantsNumber = 64 ) +var ( + expectedDomain = crypto.Keccak256([]byte("ExpectedDomain")) + unexpectedDomain = crypto.Keccak256([]byte("UnexpectedDomain")) +) + func Test_VerifySignature(t *testing.T) { t.Parallel() validTestMsg, invalidTestMsg := testGenRandomBytes(t, messageSize), testGenRandomBytes(t, messageSize) blsKey, _ := GenerateBlsKey() - signature, err := blsKey.Sign(validTestMsg, DomainValidatorSet) + signature, err := blsKey.Sign(validTestMsg, expectedDomain) require.NoError(t, err) - assert.True(t, signature.Verify(blsKey.PublicKey(), validTestMsg, DomainValidatorSet)) - assert.False(t, signature.Verify(blsKey.PublicKey(), invalidTestMsg, DomainValidatorSet)) - assert.False(t, signature.Verify(blsKey.PublicKey(), validTestMsg, DomainCheckpointManager)) + assert.True(t, signature.Verify(blsKey.PublicKey(), validTestMsg, expectedDomain)) + assert.False(t, signature.Verify(blsKey.PublicKey(), invalidTestMsg, expectedDomain)) + assert.False(t, signature.Verify(blsKey.PublicKey(), validTestMsg, unexpectedDomain)) } func Test_VerifySignature_NegativeCases(t *testing.T) { @@ -42,10 +49,10 @@ func Test_VerifySignature_NegativeCases(t *testing.T) { blsKey, err := GenerateBlsKey() require.NoError(t, err) - signature, err := blsKey.Sign(validTestMsg, DomainValidatorSet) + signature, err := blsKey.Sign(validTestMsg, expectedDomain) require.NoError(t, err) - require.True(t, signature.Verify(blsKey.PublicKey(), validTestMsg, DomainValidatorSet)) + require.True(t, signature.Verify(blsKey.PublicKey(), validTestMsg, expectedDomain)) rawSig, err := signature.Marshal() require.NoError(t, err) @@ -62,11 +69,11 @@ func Test_VerifySignature_NegativeCases(t *testing.T) { publicKey := blsKey.PublicKey() publicKey.g2.Add(publicKey.g2, randomG2) // change public key g2 point - require.False(t, sigTemp.Verify(publicKey, validTestMsg, DomainValidatorSet)) + require.False(t, sigTemp.Verify(publicKey, validTestMsg, expectedDomain)) publicKey = blsKey.PublicKey() publicKey.g2.ScalarMult(publicKey.g2, x) // change public key g2 point - require.False(t, sigTemp.Verify(publicKey, validTestMsg, DomainValidatorSet)) + require.False(t, sigTemp.Verify(publicKey, validTestMsg, expectedDomain)) } }) @@ -83,7 +90,7 @@ func Test_VerifySignature_NegativeCases(t *testing.T) { b := msgCopy[i] msgCopy[i] = b + 1 - require.False(t, sigTemp.Verify(blsKey.PublicKey(), msgCopy, DomainValidatorSet)) + require.False(t, sigTemp.Verify(blsKey.PublicKey(), msgCopy, expectedDomain)) msgCopy[i] = b } }) @@ -99,13 +106,13 @@ func Test_VerifySignature_NegativeCases(t *testing.T) { require.NoError(t, err) sigCopy.g1.Add(sigCopy.g1, randomG1) // change signature - require.False(t, sigCopy.Verify(blsKey.PublicKey(), validTestMsg, DomainValidatorSet)) + require.False(t, sigCopy.Verify(blsKey.PublicKey(), validTestMsg, expectedDomain)) sigCopy, err = UnmarshalSignature(rawSig) require.NoError(t, err) sigCopy.g1.ScalarMult(sigCopy.g1, x) // change signature - require.False(t, sigCopy.Verify(blsKey.PublicKey(), validTestMsg, DomainValidatorSet)) + require.False(t, sigCopy.Verify(blsKey.PublicKey(), validTestMsg, expectedDomain)) } }) } @@ -119,19 +126,19 @@ func Test_AggregatedSignatureSimple(t *testing.T) { bls2, _ := GenerateBlsKey() bls3, _ := GenerateBlsKey() - sig1, err := bls1.Sign(validTestMsg, DomainValidatorSet) + sig1, err := bls1.Sign(validTestMsg, expectedDomain) require.NoError(t, err) - sig2, err := bls2.Sign(validTestMsg, DomainValidatorSet) + sig2, err := bls2.Sign(validTestMsg, expectedDomain) require.NoError(t, err) - sig3, err := bls3.Sign(validTestMsg, DomainValidatorSet) + sig3, err := bls3.Sign(validTestMsg, expectedDomain) require.NoError(t, err) signatures := Signatures{sig1, sig2, sig3} publicKeys := PublicKeys{bls1.PublicKey(), bls2.PublicKey(), bls3.PublicKey()} - assert.True(t, signatures.Aggregate().Verify(publicKeys.Aggregate(), validTestMsg, DomainValidatorSet)) - assert.False(t, signatures.Aggregate().Verify(publicKeys.Aggregate(), invalidTestMsg, DomainValidatorSet)) - assert.False(t, signatures.Aggregate().Verify(publicKeys.Aggregate(), validTestMsg, DomainCheckpointManager)) + assert.True(t, signatures.Aggregate().Verify(publicKeys.Aggregate(), validTestMsg, expectedDomain)) + assert.False(t, signatures.Aggregate().Verify(publicKeys.Aggregate(), invalidTestMsg, expectedDomain)) + assert.False(t, signatures.Aggregate().Verify(publicKeys.Aggregate(), validTestMsg, unexpectedDomain)) } func Test_AggregatedSignature(t *testing.T) { @@ -154,7 +161,7 @@ func Test_AggregatedSignature(t *testing.T) { ) for _, key := range blsKeys { - signature, err := key.Sign(validTestMsg, DomainValidatorSet) + signature, err := key.Sign(validTestMsg, expectedDomain) require.NoError(t, err) signatures = append(signatures, signature) @@ -164,10 +171,10 @@ func Test_AggregatedSignature(t *testing.T) { aggSignature := signatures.Aggregate() aggPubs := publicKeys.Aggregate() - assert.True(t, aggSignature.Verify(aggPubs, validTestMsg, DomainValidatorSet)) - assert.False(t, aggSignature.Verify(aggPubs, invalidTestMsg, DomainValidatorSet)) - assert.True(t, aggSignature.VerifyAggregated([]*PublicKey(publicKeys), validTestMsg, DomainValidatorSet)) - assert.False(t, aggSignature.VerifyAggregated([]*PublicKey(publicKeys), invalidTestMsg, DomainValidatorSet)) + assert.True(t, aggSignature.Verify(aggPubs, validTestMsg, expectedDomain)) + assert.False(t, aggSignature.Verify(aggPubs, invalidTestMsg, expectedDomain)) + assert.True(t, aggSignature.VerifyAggregated([]*PublicKey(publicKeys), validTestMsg, expectedDomain)) + assert.False(t, aggSignature.VerifyAggregated([]*PublicKey(publicKeys), invalidTestMsg, expectedDomain)) } func TestSignature_BigInt(t *testing.T) { @@ -178,7 +185,7 @@ func TestSignature_BigInt(t *testing.T) { bls1, err := GenerateBlsKey() require.NoError(t, err) - sig1, err := bls1.Sign(validTestMsg, DomainCheckpointManager) + sig1, err := bls1.Sign(validTestMsg, unexpectedDomain) assert.NoError(t, err) _, err = sig1.ToBigInt() @@ -193,7 +200,7 @@ func TestSignature_Unmarshal(t *testing.T) { bls1, err := GenerateBlsKey() require.NoError(t, err) - sig, err := bls1.Sign(validTestMsg, DomainCheckpointManager) + sig, err := bls1.Sign(validTestMsg, unexpectedDomain) require.NoError(t, err) bytes, err := sig.Marshal() diff --git a/consensus/polybft/signer/testcases/hashToPoint.json b/bls/testcases/hashToPoint.json similarity index 100% rename from consensus/polybft/signer/testcases/hashToPoint.json rename to bls/testcases/hashToPoint.json diff --git a/consensus/polybft/signer/common.go b/bls/utils.go similarity index 60% rename from consensus/polybft/signer/common.go rename to bls/utils.go index e39f26cbe6..2b9c0a8d9a 100644 --- a/consensus/polybft/signer/common.go +++ b/bls/utils.go @@ -3,40 +3,46 @@ package bls import ( "crypto/rand" "encoding/hex" - "fmt" "io" "log" "math/big" - pcrypto "github.com/0xPolygon/polygon-edge/crypto" bn256 "github.com/umbracle/go-eth-bn256" ) -const ( - DomainValidatorSetString = "DOMAIN_CHILD_VALIDATOR_SET" - DomainCheckpointManagerString = "DOMAIN_CHECKPOINT_MANAGER" - DomainCommonSigningString = "DOMAIN_COMMON_SIGNING" - DomainStateReceiverString = "DOMAIN_STATE_RECEIVER" -) - -var errInfinityPoint = fmt.Errorf("infinity point") - var ( // negated g2 point negG2Point = mustG2Point("198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c21800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed275dc4a288d1afb3cbb1ac09187524c7db36395df7be3b99e673b13a075a65ec1d9befcd05a5323e6da4d435f3b617cdb3af83285c2df711ef39c01571827f9d") //nolint // g2 point g2Point = mustG2Point("198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c21800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa") //nolint +) + +// GenerateBlsKey creates a random private key (and its corresponding public key) +func GenerateBlsKey() (*PrivateKey, error) { + s, err := randomK(rand.Reader) + if err != nil { + return nil, err + } - // domain used to map hash to G1 used by (child) validator set - DomainValidatorSet = pcrypto.Keccak256([]byte(DomainValidatorSetString)) + return &PrivateKey{s: s}, nil +} - // domain used to map hash to G1 used by child checkpoint manager - DomainCheckpointManager = pcrypto.Keccak256([]byte(DomainCheckpointManagerString)) +// CreateRandomBlsKeys creates an array of random private and their corresponding public keys +func CreateRandomBlsKeys(total int) ([]*PrivateKey, error) { + blsKeys := make([]*PrivateKey, total) - DomainCommonSigning = pcrypto.Keccak256([]byte(DomainCommonSigningString)) - DomainStateReceiver = pcrypto.Keccak256([]byte(DomainStateReceiverString)) -) + for i := 0; i < total; i++ { + blsKey, err := GenerateBlsKey() + if err != nil { + return nil, err + } + + blsKeys[i] = blsKey + } + + return blsKeys, nil +} func mustG2Point(str string) *bn256.G2 { buf, err := hex.DecodeString(str) diff --git a/bls/utils_test.go b/bls/utils_test.go new file mode 100644 index 0000000000..0d03845772 --- /dev/null +++ b/bls/utils_test.go @@ -0,0 +1,66 @@ +package bls + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func Test_SingleSign(t *testing.T) { + t.Parallel() + + validTestMsg, invalidTestMsg := testGenRandomBytes(t, messageSize), testGenRandomBytes(t, messageSize) + + blsKey, err := GenerateBlsKey() // structure which holds private/public key pair + require.NoError(t, err) + + // Sign valid message + signature, err := blsKey.Sign(validTestMsg, expectedDomain) + require.NoError(t, err) + + isOk := signature.Verify(blsKey.PublicKey(), validTestMsg, expectedDomain) + assert.True(t, isOk) + + // Verify if invalid message is signed with correct private key. Only use public key for the verification + // this should fail => isOk = false + isOk = signature.Verify(blsKey.PublicKey(), invalidTestMsg, unexpectedDomain) + assert.False(t, isOk) +} + +func Test_AggregatedSign(t *testing.T) { + t.Parallel() + + validTestMsg, invalidTestMsg := testGenRandomBytes(t, messageSize), testGenRandomBytes(t, messageSize) + + keys, err := CreateRandomBlsKeys(participantsNumber) // create keys for validators + require.NoError(t, err) + + pubKeys := make([]*PublicKey, len(keys)) + + for i, key := range keys { + pubKeys[i] = key.PublicKey() + } + + signatures := Signatures{} + + // test all signatures at once + for i := 0; i < len(keys); i++ { + sign, err := keys[i].Sign(validTestMsg, expectedDomain) + require.NoError(t, err) + + signatures = append(signatures, sign) + + // verify correctness of AggregateSignature + aggSig := signatures.Aggregate() + + isOk := aggSig.VerifyAggregated(pubKeys[:i+1], validTestMsg, expectedDomain) + assert.True(t, isOk) + + isOk = aggSig.VerifyAggregated(pubKeys[:i+1], invalidTestMsg, expectedDomain) + assert.False(t, isOk) + + isOk = aggSig.VerifyAggregated(pubKeys[:i+1], validTestMsg, unexpectedDomain) + assert.False(t, isOk) + } +} diff --git a/command/polybftsecrets/params_test.go b/command/polybftsecrets/params_test.go index c9cbd0aa15..f811d52ee9 100644 --- a/command/polybftsecrets/params_test.go +++ b/command/polybftsecrets/params_test.go @@ -6,11 +6,12 @@ import ( "path" "testing" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" - "github.com/0xPolygon/polygon-edge/secrets/helper" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/umbracle/ethgo/wallet" + + "github.com/0xPolygon/polygon-edge/bls" + "github.com/0xPolygon/polygon-edge/secrets/helper" ) // Test initKeys diff --git a/command/rootchain/deploy/deploy.go b/command/rootchain/deploy/deploy.go index a631735568..3d5b16e9e0 100644 --- a/command/rootchain/deploy/deploy.go +++ b/command/rootchain/deploy/deploy.go @@ -18,7 +18,7 @@ import ( "github.com/0xPolygon/polygon-edge/consensus/polybft" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi/artifact" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/contracts" "github.com/0xPolygon/polygon-edge/txrelayer" @@ -125,7 +125,7 @@ var ( NewMatic: types.StringToAddress(params.stakeTokenAddr), NewChildValidatorSet: contracts.ValidatorSetContract, NewExitHelper: config.ExitHelperAddress, - NewDomain: bls.DomainValidatorSetString, + NewDomain: signer.DomainValidatorSetString, } return initContract(fmt, relayer, initParams, diff --git a/command/rootchain/registration/register_validator.go b/command/rootchain/registration/register_validator.go index 74dc948efb..eeee113c86 100644 --- a/command/rootchain/registration/register_validator.go +++ b/command/rootchain/registration/register_validator.go @@ -5,12 +5,13 @@ import ( "errors" "fmt" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/command" "github.com/0xPolygon/polygon-edge/command/helper" "github.com/0xPolygon/polygon-edge/command/polybftsecrets" rootHelper "github.com/0xPolygon/polygon-edge/command/rootchain/helper" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" @@ -89,9 +90,9 @@ func runCommand(cmd *cobra.Command, _ []string) error { return err } - koskSignature, err := bls.MakeKOSKSignature( + koskSignature, err := signer.MakeKOSKSignature( newValidatorAccount.Bls, newValidatorAccount.Address(), - rootChainID.Int64(), bls.DomainValidatorSet, types.StringToAddress(params.supernetManagerAddress)) + rootChainID.Int64(), signer.DomainValidatorSet, types.StringToAddress(params.supernetManagerAddress)) if err != nil { return err } diff --git a/consensus/polybft/checkpoint_manager.go b/consensus/polybft/checkpoint_manager.go index 92fdd97d5b..d8098f1f6d 100644 --- a/consensus/polybft/checkpoint_manager.go +++ b/consensus/polybft/checkpoint_manager.go @@ -6,8 +6,8 @@ import ( "math/big" "strconv" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/contracts" "github.com/0xPolygon/polygon-edge/helper/hex" diff --git a/consensus/polybft/checkpoint_manager_test.go b/consensus/polybft/checkpoint_manager_test.go index 760e6b5a67..5b46a0469d 100644 --- a/consensus/polybft/checkpoint_manager_test.go +++ b/consensus/polybft/checkpoint_manager_test.go @@ -11,6 +11,7 @@ import ( "github.com/umbracle/ethgo/jsonrpc" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/contracts" "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/merkle-tree" @@ -19,8 +20,8 @@ import ( "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/txrelayer" @@ -66,7 +67,7 @@ func TestCheckpointManager_SubmitCheckpoint(t *testing.T) { validators.IterAcct(aliases, func(t *validator.TestValidator) { bitmap.Set(idx) - signatures = append(signatures, t.MustSign(dummyMsg, bls.DomainCheckpointManager)) + signatures = append(signatures, t.MustSign(dummyMsg, signer.DomainCheckpointManager)) idx++ }) @@ -170,7 +171,7 @@ func TestCheckpointManager_abiEncodeCheckpointBlock(t *testing.T) { var signatures bls.Signatures currentValidators.IterAcct(nil, func(v *validator.TestValidator) { - signatures = append(signatures, v.MustSign(proposalHash, bls.DomainCheckpointManager)) + signatures = append(signatures, v.MustSign(proposalHash, signer.DomainCheckpointManager)) bmp.Set(i) i++ }) diff --git a/consensus/polybft/consensus_runtime.go b/consensus/polybft/consensus_runtime.go index 288a810daf..f3068f7b61 100644 --- a/consensus/polybft/consensus_runtime.go +++ b/consensus/polybft/consensus_runtime.go @@ -12,7 +12,7 @@ import ( "github.com/0xPolygon/polygon-edge/consensus" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/contracts" @@ -983,7 +983,7 @@ func (c *consensusRuntime) BuildPrepareMessage(proposalHash []byte, view *proto. // BuildCommitMessage builds a COMMIT message based on the passed in proposal func (c *consensusRuntime) BuildCommitMessage(proposalHash []byte, view *proto.View) *proto.Message { - committedSeal, err := c.config.Key.SignWithDomain(proposalHash, bls.DomainCheckpointManager) + committedSeal, err := c.config.Key.SignWithDomain(proposalHash, signer.DomainCheckpointManager) if err != nil { c.logger.Error("Cannot create committed seal message.", "error", err) diff --git a/consensus/polybft/consensus_runtime_test.go b/consensus/polybft/consensus_runtime_test.go index 6909bf3839..a466485ea6 100644 --- a/consensus/polybft/consensus_runtime_test.go +++ b/consensus/polybft/consensus_runtime_test.go @@ -11,7 +11,7 @@ import ( "github.com/0xPolygon/go-ibft/messages/proto" "github.com/0xPolygon/polygon-edge/consensus" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/contracts" @@ -702,7 +702,7 @@ func TestConsensusRuntime_TamperMessageContent(t *testing.T) { } sender := validatorAccounts.GetValidator("A") proposalHash := []byte{2, 4, 6, 8, 10} - proposalSignature, err := sender.Key().SignWithDomain(proposalHash, bls.DomainCheckpointManager) + proposalSignature, err := sender.Key().SignWithDomain(proposalHash, signer.DomainCheckpointManager) require.NoError(t, err) msg := &proto.Message{ @@ -924,7 +924,7 @@ func TestConsensusRuntime_BuildCommitMessage(t *testing.T) { }, } - committedSeal, err := key.SignWithDomain(proposalHash, bls.DomainCheckpointManager) + committedSeal, err := key.SignWithDomain(proposalHash, signer.DomainCheckpointManager) require.NoError(t, err) expected := proto.Message{ diff --git a/consensus/polybft/extra.go b/consensus/polybft/extra.go index 16fdd7e420..50bef0fc58 100644 --- a/consensus/polybft/extra.go +++ b/consensus/polybft/extra.go @@ -4,7 +4,7 @@ import ( "fmt" "math/big" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/types" diff --git a/consensus/polybft/extra_test.go b/consensus/polybft/extra_test.go index 2f5c1a019a..84629d77e9 100644 --- a/consensus/polybft/extra_test.go +++ b/consensus/polybft/extra_test.go @@ -8,9 +8,10 @@ import ( mrand "math/rand" "testing" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/chain" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/crypto" @@ -197,7 +198,7 @@ func TestExtra_UnmarshalRLPWith_NegativeCases(t *testing.T) { key, err := wallet.GenerateAccount() require.NoError(t, err) - parentSignature := createSignature(t, []*wallet.Account{key}, types.BytesToHash([]byte("This is test hash")), bls.DomainCheckpointManager) + parentSignature := createSignature(t, []*wallet.Account{key}, types.BytesToHash([]byte("This is test hash")), signer.DomainCheckpointManager) extraMarshalled.Set(parentSignature.MarshalRLPWith(ar)) // Committed @@ -220,11 +221,11 @@ func TestExtra_UnmarshalRLPWith_NegativeCases(t *testing.T) { key, err := wallet.GenerateAccount() require.NoError(t, err) - parentSignature := createSignature(t, []*wallet.Account{key}, types.BytesToHash(generateRandomBytes(t)), bls.DomainCheckpointManager) + parentSignature := createSignature(t, []*wallet.Account{key}, types.BytesToHash(generateRandomBytes(t)), signer.DomainCheckpointManager) extraMarshalled.Set(parentSignature.MarshalRLPWith(ar)) // Committed - committedSignature := createSignature(t, []*wallet.Account{key}, types.BytesToHash(generateRandomBytes(t)), bls.DomainCheckpointManager) + committedSignature := createSignature(t, []*wallet.Account{key}, types.BytesToHash(generateRandomBytes(t)), signer.DomainCheckpointManager) extraMarshalled.Set(committedSignature.MarshalRLPWith(ar)) // Checkpoint data @@ -262,13 +263,13 @@ func TestExtra_ValidateFinalizedData_UnhappyPath(t *testing.T) { // missing Committed field extra := &Extra{} err := extra.ValidateFinalizedData( - header, parent, nil, chainID, nil, bls.DomainCheckpointManager, hclog.NewNullLogger()) + header, parent, nil, chainID, nil, signer.DomainCheckpointManager, hclog.NewNullLogger()) require.ErrorContains(t, err, fmt.Sprintf("failed to verify signatures for block %d, because signatures are not present", headerNum)) // missing Checkpoint field extra = &Extra{Committed: &Signature{}} err = extra.ValidateFinalizedData( - header, parent, nil, chainID, polyBackendMock, bls.DomainCheckpointManager, hclog.NewNullLogger()) + header, parent, nil, chainID, polyBackendMock, signer.DomainCheckpointManager, hclog.NewNullLogger()) require.ErrorContains(t, err, fmt.Sprintf("failed to verify signatures for block %d, because checkpoint data are not present", headerNum)) // failed to retrieve validators from snapshot @@ -279,7 +280,7 @@ func TestExtra_ValidateFinalizedData_UnhappyPath(t *testing.T) { } extra = &Extra{Committed: &Signature{}, Checkpoint: checkpoint} err = extra.ValidateFinalizedData( - header, parent, nil, chainID, polyBackendMock, bls.DomainCheckpointManager, hclog.NewNullLogger()) + header, parent, nil, chainID, polyBackendMock, signer.DomainCheckpointManager, hclog.NewNullLogger()) require.ErrorContains(t, err, fmt.Sprintf("failed to validate header for block %d. could not retrieve block validators:validators not found", headerNum)) @@ -287,21 +288,21 @@ func TestExtra_ValidateFinalizedData_UnhappyPath(t *testing.T) { polyBackendMock = new(polybftBackendMock) polyBackendMock.On("GetValidators", mock.Anything, mock.Anything).Return(validators.GetPublicIdentities()) - noQuorumSignature := createSignature(t, validators.GetPrivateIdentities("0", "1"), types.BytesToHash([]byte("FooBar")), bls.DomainCheckpointManager) + noQuorumSignature := createSignature(t, validators.GetPrivateIdentities("0", "1"), types.BytesToHash([]byte("FooBar")), signer.DomainCheckpointManager) extra = &Extra{Committed: noQuorumSignature, Checkpoint: checkpoint} checkpointHash, err := checkpoint.Hash(chainID, headerNum, header.Hash) require.NoError(t, err) err = extra.ValidateFinalizedData( - header, parent, nil, chainID, polyBackendMock, bls.DomainCheckpointManager, hclog.NewNullLogger()) + header, parent, nil, chainID, polyBackendMock, signer.DomainCheckpointManager, hclog.NewNullLogger()) require.ErrorContains(t, err, fmt.Sprintf("failed to verify signatures for block %d (proposal hash %s): quorum not reached", headerNum, checkpointHash)) // incorrect parent extra size - validSignature := createSignature(t, validators.GetPrivateIdentities(), checkpointHash, bls.DomainCheckpointManager) + validSignature := createSignature(t, validators.GetPrivateIdentities(), checkpointHash, signer.DomainCheckpointManager) extra = &Extra{Committed: validSignature, Checkpoint: checkpoint} err = extra.ValidateFinalizedData( - header, parent, nil, chainID, polyBackendMock, bls.DomainCheckpointManager, hclog.NewNullLogger()) + header, parent, nil, chainID, polyBackendMock, signer.DomainCheckpointManager, hclog.NewNullLogger()) require.ErrorContains(t, err, fmt.Sprintf("failed to verify signatures for block %d: wrong extra size: 0", headerNum)) } @@ -320,21 +321,21 @@ func TestExtra_ValidateParentSignatures(t *testing.T) { // validation is skipped for blocks 0 and 1 extra := &Extra{} err := extra.ValidateParentSignatures( - 1, polyBackendMock, nil, nil, nil, chainID, bls.DomainCheckpointManager, hclog.NewNullLogger()) + 1, polyBackendMock, nil, nil, nil, chainID, signer.DomainCheckpointManager, hclog.NewNullLogger()) require.NoError(t, err) // parent signatures not present err = extra.ValidateParentSignatures( - headerNum, polyBackendMock, nil, nil, nil, chainID, bls.DomainCheckpointManager, hclog.NewNullLogger()) + headerNum, polyBackendMock, nil, nil, nil, chainID, signer.DomainCheckpointManager, hclog.NewNullLogger()) require.ErrorContains(t, err, fmt.Sprintf("failed to verify signatures for parent of block %d because signatures are not present", headerNum)) // validators not found validators := validator.NewTestValidators(t, 5) incorrectHash := types.BytesToHash([]byte("Hello World")) - invalidSig := createSignature(t, validators.GetPrivateIdentities(), incorrectHash, bls.DomainCheckpointManager) + invalidSig := createSignature(t, validators.GetPrivateIdentities(), incorrectHash, signer.DomainCheckpointManager) extra = &Extra{Parent: invalidSig} err = extra.ValidateParentSignatures( - headerNum, polyBackendMock, nil, nil, nil, chainID, bls.DomainCheckpointManager, hclog.NewNullLogger()) + headerNum, polyBackendMock, nil, nil, nil, chainID, signer.DomainCheckpointManager, hclog.NewNullLogger()) require.ErrorContains(t, err, fmt.Sprintf("failed to validate header for block %d. could not retrieve parent validators: no validators", headerNum)) @@ -350,15 +351,15 @@ func TestExtra_ValidateParentSignatures(t *testing.T) { require.NoError(t, err) err = extra.ValidateParentSignatures( - headerNum, polyBackendMock, nil, parent, parentExtra, chainID, bls.DomainCheckpointManager, hclog.NewNullLogger()) + headerNum, polyBackendMock, nil, parent, parentExtra, chainID, signer.DomainCheckpointManager, hclog.NewNullLogger()) require.ErrorContains(t, err, fmt.Sprintf("failed to verify signatures for parent of block %d (proposal hash: %s): could not verify aggregated signature", headerNum, parentCheckpointHash)) // valid signature provided - validSig := createSignature(t, validators.GetPrivateIdentities(), parentCheckpointHash, bls.DomainCheckpointManager) + validSig := createSignature(t, validators.GetPrivateIdentities(), parentCheckpointHash, signer.DomainCheckpointManager) extra = &Extra{Parent: validSig} err = extra.ValidateParentSignatures( - headerNum, polyBackendMock, nil, parent, parentExtra, chainID, bls.DomainCheckpointManager, hclog.NewNullLogger()) + headerNum, polyBackendMock, nil, parent, parentExtra, chainID, signer.DomainCheckpointManager, hclog.NewNullLogger()) require.NoError(t, err) } @@ -382,7 +383,7 @@ func TestSignature_Verify(t *testing.T) { for i, val := range vals.GetValidators() { bitmap.Set(uint64(i)) - tempSign, err := val.Account.Bls.Sign(msgHash[:], bls.DomainCheckpointManager) + tempSign, err := val.Account.Bls.Sign(msgHash[:], signer.DomainCheckpointManager) require.NoError(t, err) signatures = append(signatures, tempSign) @@ -394,7 +395,7 @@ func TestSignature_Verify(t *testing.T) { Bitmap: bitmap, } - err = s.Verify(10, validatorsMetadata, msgHash, bls.DomainCheckpointManager, hclog.NewNullLogger()) + err = s.Verify(10, validatorsMetadata, msgHash, signer.DomainCheckpointManager, hclog.NewNullLogger()) signers[val.Address()] = struct{}{} if !validatorSet.HasQuorum(10, signers) { @@ -415,7 +416,7 @@ func TestSignature_Verify(t *testing.T) { bmp.Set(uint64(validatorSet.Len() + 1)) s := &Signature{Bitmap: bmp} - err := s.Verify(0, validatorSet, types.Hash{0x1}, bls.DomainCheckpointManager, hclog.NewNullLogger()) + err := s.Verify(0, validatorSet, types.Hash{0x1}, signer.DomainCheckpointManager, hclog.NewNullLogger()) require.Error(t, err) }) } @@ -469,7 +470,7 @@ func TestSignature_VerifyRandom(t *testing.T) { for _, index := range valIndxsRnd { bitmap.Set(uint64(index)) - tempSign, err := accounts[index].Account.Bls.Sign(msgHash[:], bls.DomainCheckpointManager) + tempSign, err := accounts[index].Account.Bls.Sign(msgHash[:], signer.DomainCheckpointManager) require.NoError(t, err) signature = append(signature, tempSign) @@ -483,7 +484,7 @@ func TestSignature_VerifyRandom(t *testing.T) { Bitmap: bitmap, } - err = s.Verify(1, vals.GetPublicIdentities(), msgHash, bls.DomainCheckpointManager, hclog.NewNullLogger()) + err = s.Verify(1, vals.GetPublicIdentities(), msgHash, signer.DomainCheckpointManager, hclog.NewNullLogger()) assert.NoError(t, err) } diff --git a/consensus/polybft/fsm.go b/consensus/polybft/fsm.go index 141fcb9570..59360cc997 100644 --- a/consensus/polybft/fsm.go +++ b/consensus/polybft/fsm.go @@ -9,16 +9,18 @@ import ( "github.com/0xPolygon/go-ibft/messages" "github.com/0xPolygon/go-ibft/messages/proto" + "github.com/armon/go-metrics" + hcf "github.com/hashicorp/go-hclog" + + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/contracts" "github.com/0xPolygon/polygon-edge/state" "github.com/0xPolygon/polygon-edge/types" - "github.com/armon/go-metrics" - hcf "github.com/hashicorp/go-hclog" ) type blockBuilder interface { @@ -270,8 +272,8 @@ func (f *fsm) createDistributeRewardsTx() (*types.Transaction, error) { } // ValidateCommit is used to validate that a given commit is valid -func (f *fsm) ValidateCommit(signer []byte, seal []byte, proposalHash []byte) error { - from := types.BytesToAddress(signer) +func (f *fsm) ValidateCommit(signerAddr []byte, seal []byte, proposalHash []byte) error { + from := types.BytesToAddress(signerAddr) validator := f.validators.Accounts().GetValidatorMetadata(from) if validator == nil { @@ -283,7 +285,7 @@ func (f *fsm) ValidateCommit(signer []byte, seal []byte, proposalHash []byte) er return fmt.Errorf("failed to unmarshall signature: %w", err) } - if !signature.Verify(validator.BlsKey, proposalHash, bls.DomainCheckpointManager) { + if !signature.Verify(validator.BlsKey, proposalHash, signer.DomainCheckpointManager) { return fmt.Errorf("incorrect commit signature from %s", from) } @@ -326,7 +328,7 @@ func (f *fsm) Validate(proposal []byte) error { } if err := extra.ValidateParentSignatures(block.Number(), f.polybftBackend, nil, f.parent, parentExtra, - f.backend.GetChainID(), bls.DomainCheckpointManager, f.logger); err != nil { + f.backend.GetChainID(), signer.DomainCheckpointManager, f.logger); err != nil { return err } @@ -645,7 +647,7 @@ func verifyBridgeCommitmentTx(blockNumber uint64, txHash types.Hash, return fmt.Errorf("error for state tx (%s) while unmarshaling signature: %w", txHash, err) } - verified := signature.VerifyAggregated(signers.GetBlsKeys(), commitmentHash.Bytes(), bls.DomainStateReceiver) + verified := signature.VerifyAggregated(signers.GetBlsKeys(), commitmentHash.Bytes(), signer.DomainStateReceiver) if !verified { return fmt.Errorf("invalid signature for state tx (%s)", txHash) } diff --git a/consensus/polybft/fsm_test.go b/consensus/polybft/fsm_test.go index 4fde9a537b..105e366e9c 100644 --- a/consensus/polybft/fsm_test.go +++ b/consensus/polybft/fsm_test.go @@ -10,10 +10,11 @@ import ( "github.com/0xPolygon/go-ibft/messages" "github.com/0xPolygon/go-ibft/messages/proto" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/contracts" @@ -598,7 +599,7 @@ func TestFSM_VerifyStateTransactions_StateTransactionInvalidSignature(t *testing aggregatedSigs := bls.Signatures{} nonValidators.IterAcct(nil, func(t *validator.TestValidator) { - aggregatedSigs = append(aggregatedSigs, t.MustSign([]byte("dummyHash"), bls.DomainStateReceiver)) + aggregatedSigs = append(aggregatedSigs, t.MustSign([]byte("dummyHash"), signer.DomainStateReceiver)) }) sig, err := aggregatedSigs.Aggregate().Marshal() @@ -682,7 +683,7 @@ func TestFSM_ValidateCommit_InvalidHash(t *testing.T) { require.NoError(t, err) nonValidatorAcc := validator.NewTestValidator(t, "non_validator", 1) - wrongSignature, err := nonValidatorAcc.MustSign([]byte("Foo"), bls.DomainCheckpointManager).Marshal() + wrongSignature, err := nonValidatorAcc.MustSign([]byte("Foo"), signer.DomainCheckpointManager).Marshal() require.NoError(t, err) err = fsm.ValidateCommit(validators.GetValidator("0").Address().Bytes(), wrongSignature, []byte{}) @@ -716,7 +717,7 @@ func TestFSM_ValidateCommit_Good(t *testing.T) { require.NoError(t, block.UnmarshalRLP(proposal)) validator := validators.GetValidator("A") - seal, err := validator.MustSign(block.Hash().Bytes(), bls.DomainCheckpointManager).Marshal() + seal, err := validator.MustSign(block.Hash().Bytes(), signer.DomainCheckpointManager).Marshal() require.NoError(t, err) err = fsm.ValidateCommit(validator.Key().Address().Bytes(), seal, block.Hash().Bytes()) require.NoError(t, err) @@ -752,7 +753,7 @@ func TestFSM_Validate_ExitEventRootNotExpected(t *testing.T) { currentValSetHash, err := validators.GetPublicIdentities().Hash() require.NoError(t, err) - extra.Parent = createSignature(t, validators.GetPrivateIdentities(), parentCheckpointHash, bls.DomainCheckpointManager) + extra.Parent = createSignature(t, validators.GetPrivateIdentities(), parentCheckpointHash, signer.DomainCheckpointManager) extra.Checkpoint.EpochNumber = 1 extra.Checkpoint.CurrentValidatorsHash = currentValSetHash extra.Checkpoint.NextValidatorsHash = currentValSetHash @@ -812,7 +813,7 @@ func TestFSM_Validate_EpochEndingBlock_MismatchInDeltas(t *testing.T) { require.NoError(t, err) extra.Validators = &validator.ValidatorSetDelta{} // this will cause test to fail - extra.Parent = createSignature(t, validators.GetPrivateIdentities(), parentCheckpointHash, bls.DomainCheckpointManager) + extra.Parent = createSignature(t, validators.GetPrivateIdentities(), parentCheckpointHash, signer.DomainCheckpointManager) stateBlock := createDummyStateBlock(parent.Number+1, types.Hash{100, 15}, extra.MarshalRLPTo(nil)) @@ -915,7 +916,7 @@ func TestFSM_Validate_EpochEndingBlock_UpdatingValidatorSetInNonEpochEndingBlock require.NoError(t, err) extra.Validators = newValidatorDelta // this will cause test to fail - extra.Parent = createSignature(t, validators.GetPrivateIdentities(), parentCheckpointHash, bls.DomainCheckpointManager) + extra.Parent = createSignature(t, validators.GetPrivateIdentities(), parentCheckpointHash, signer.DomainCheckpointManager) stateBlock := createDummyStateBlock(parent.Number+1, types.Hash{100, 15}, extra.MarshalRLPTo(nil)) @@ -1153,7 +1154,7 @@ func TestFSM_Insert_Good(t *testing.T) { seals := make([]*messages.CommittedSeal, signaturesCount) for i := 0; i < signaturesCount; i++ { - sign, err := allAccounts[i].Bls.Sign(builtBlock.Block.Hash().Bytes(), bls.DomainCheckpointManager) + sign, err := allAccounts[i].Bls.Sign(builtBlock.Block.Hash().Bytes(), signer.DomainCheckpointManager) require.NoError(t, err) sigRaw, err := sign.Marshal() require.NoError(t, err) @@ -1237,15 +1238,15 @@ func TestFSM_Insert_InvalidNode(t *testing.T) { validatorA := validators.GetValidator("A") validatorB := validators.GetValidator("B") proposalHash := buildBlock.Block.Hash().Bytes() - sigA, err := validatorA.MustSign(proposalHash, bls.DomainCheckpointManager).Marshal() + sigA, err := validatorA.MustSign(proposalHash, signer.DomainCheckpointManager).Marshal() require.NoError(t, err) - sigB, err := validatorB.MustSign(proposalHash, bls.DomainCheckpointManager).Marshal() + sigB, err := validatorB.MustSign(proposalHash, signer.DomainCheckpointManager).Marshal() require.NoError(t, err) // create test account outside of validator set nonValidatorAccount := validator.NewTestValidator(t, "non_validator", 1) - nonValidatorSignature, err := nonValidatorAccount.MustSign(proposalHash, bls.DomainCheckpointManager).Marshal() + nonValidatorSignature, err := nonValidatorAccount.MustSign(proposalHash, signer.DomainCheckpointManager).Marshal() require.NoError(t, err) commitedSeals := []*messages.CommittedSeal{ @@ -1337,7 +1338,7 @@ func TestFSM_VerifyStateTransaction_ValidBothTypesOfStateTransactions(t *testing // add register commitment state transaction hash, err := sc.Hash() require.NoError(t, err) - signature := createSignature(t, validators.GetPrivateIdentities(aliases...), hash, bls.DomainStateReceiver) + signature := createSignature(t, validators.GetPrivateIdentities(aliases...), hash, signer.DomainStateReceiver) sc.AggSignature = *signature } @@ -1396,7 +1397,7 @@ func TestFSM_VerifyStateTransaction_QuorumNotReached(t *testing.T) { var txns []*types.Transaction - signature := createSignature(t, validators.GetPrivateIdentities("A", "B"), hash, bls.DomainStateReceiver) + signature := createSignature(t, validators.GetPrivateIdentities("A", "B"), hash, signer.DomainStateReceiver) commitmentMessageSigned.AggSignature = *signature inputData, err := commitmentMessageSigned.EncodeAbi() @@ -1425,9 +1426,9 @@ func TestFSM_VerifyStateTransaction_InvalidSignature(t *testing.T) { var txns []*types.Transaction - signature := createSignature(t, validators.GetPrivateIdentities("A", "B", "C", "D"), hash, bls.DomainStateReceiver) + signature := createSignature(t, validators.GetPrivateIdentities("A", "B", "C", "D"), hash, signer.DomainStateReceiver) invalidValidator := validator.NewTestValidator(t, "G", 1) - invalidSignature, err := invalidValidator.MustSign([]byte("malicious message"), bls.DomainStateReceiver).Marshal() + invalidSignature, err := invalidValidator.MustSign([]byte("malicious message"), signer.DomainStateReceiver).Marshal() require.NoError(t, err) commitmentMessageSigned.AggSignature = Signature{ @@ -1463,7 +1464,7 @@ func TestFSM_VerifyStateTransaction_TwoCommitmentMessages(t *testing.T) { var txns []*types.Transaction - signature := createSignature(t, validators.GetPrivateIdentities("A", "B", "C", "D"), hash, bls.DomainStateReceiver) + signature := createSignature(t, validators.GetPrivateIdentities("A", "B", "C", "D"), hash, signer.DomainStateReceiver) commitmentMessageSigned.AggSignature = *signature inputData, err := commitmentMessageSigned.EncodeAbi() @@ -1593,7 +1594,7 @@ func createTestCommitment(t *testing.T, accounts []*wallet.Account) *CommitmentM var signatures bls.Signatures for _, a := range accounts { - signature, err := a.Bls.Sign(hash.Bytes(), bls.DomainStateReceiver) + signature, err := a.Bls.Sign(hash.Bytes(), signer.DomainStateReceiver) assert.NoError(t, err) signatures = append(signatures, signature) diff --git a/consensus/polybft/hash_test.go b/consensus/polybft/hash_test.go index 314a9dcc51..1e4f0da978 100644 --- a/consensus/polybft/hash_test.go +++ b/consensus/polybft/hash_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/types" @@ -14,7 +14,7 @@ import ( func Test_setupHeaderHashFunc(t *testing.T) { extra := &Extra{ Validators: &validator.ValidatorSetDelta{Removed: bitmap.Bitmap{1}}, - Parent: createSignature(t, []*wallet.Account{generateTestAccount(t)}, types.ZeroHash, bls.DomainCheckpointManager), + Parent: createSignature(t, []*wallet.Account{generateTestAccount(t)}, types.ZeroHash, signer.DomainCheckpointManager), Checkpoint: &CheckpointData{}, Committed: &Signature{}, } @@ -28,7 +28,7 @@ func Test_setupHeaderHashFunc(t *testing.T) { header.ExtraData = extra.MarshalRLPTo(nil) notFullExtraHash := types.HeaderHash(header) - extra.Committed = createSignature(t, []*wallet.Account{generateTestAccount(t)}, types.ZeroHash, bls.DomainCheckpointManager) + extra.Committed = createSignature(t, []*wallet.Account{generateTestAccount(t)}, types.ZeroHash, signer.DomainCheckpointManager) header.ExtraData = extra.MarshalRLPTo(nil) fullExtraHash := types.HeaderHash(header) diff --git a/consensus/polybft/helpers_test.go b/consensus/polybft/helpers_test.go index 7d8ed09231..a002e1efb6 100644 --- a/consensus/polybft/helpers_test.go +++ b/consensus/polybft/helpers_test.go @@ -9,9 +9,9 @@ import ( "testing" "time" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/types" diff --git a/consensus/polybft/polybft.go b/consensus/polybft/polybft.go index 9ebf2fae75..0b85c59661 100644 --- a/consensus/polybft/polybft.go +++ b/consensus/polybft/polybft.go @@ -16,7 +16,7 @@ import ( "github.com/0xPolygon/polygon-edge/chain" "github.com/0xPolygon/polygon-edge/consensus" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/contracts" @@ -723,7 +723,7 @@ func (p *Polybft) verifyHeaderImpl(parent, header *types.Header, blockTimeDrift // validate extra data return extra.ValidateFinalizedData( - header, parent, parents, p.blockchain.GetChainID(), p, bls.DomainCheckpointManager, p.logger) + header, parent, parents, p.blockchain.GetChainID(), p, signer.DomainCheckpointManager, p.logger) } func (p *Polybft) GetValidators(blockNumber uint64, parents []*types.Header) (validator.AccountSet, error) { diff --git a/consensus/polybft/polybft_test.go b/consensus/polybft/polybft_test.go index 8d8f44f10f..781e0e84fa 100644 --- a/consensus/polybft/polybft_test.go +++ b/consensus/polybft/polybft_test.go @@ -7,7 +7,7 @@ import ( "github.com/0xPolygon/polygon-edge/chain" "github.com/0xPolygon/polygon-edge/consensus" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/helper/progress" @@ -56,7 +56,7 @@ func TestPolybft_VerifyHeader(t *testing.T) { checkpointHash, err := extra.Checkpoint.Hash(0, header.Number, header.Hash) require.NoError(t, err) - extra.Committed = createSignature(t, committedAccounts, checkpointHash, bls.DomainCheckpointManager) + extra.Committed = createSignature(t, committedAccounts, checkpointHash, signer.DomainCheckpointManager) header.ExtraData = extra.MarshalRLPTo(nil) } diff --git a/consensus/polybft/proposer_calculator_test.go b/consensus/polybft/proposer_calculator_test.go index a746468e21..83018701c6 100644 --- a/consensus/polybft/proposer_calculator_test.go +++ b/consensus/polybft/proposer_calculator_test.go @@ -5,7 +5,7 @@ import ( "math/big" "testing" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/types" "github.com/hashicorp/go-hclog" diff --git a/consensus/polybft/sc_integration_test.go b/consensus/polybft/sc_integration_test.go index 0bf377ccfa..c352853cbe 100644 --- a/consensus/polybft/sc_integration_test.go +++ b/consensus/polybft/sc_integration_test.go @@ -11,10 +11,11 @@ import ( "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/abi" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/chain" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/contracts" "github.com/0xPolygon/polygon-edge/crypto" @@ -205,7 +206,7 @@ func TestIntegration_PerformExit(t *testing.T) { signatures := bls.Signatures(nil) currentValidators.IterAcct(nil, func(v *validator.TestValidator) { - signatures = append(signatures, v.MustSign(checkpointHash[:], bls.DomainCheckpointManager)) + signatures = append(signatures, v.MustSign(checkpointHash[:], signer.DomainCheckpointManager)) bmp.Set(i) i++ }) diff --git a/consensus/polybft/signer/utils.go b/consensus/polybft/signer/utils.go index 0117714517..5628167667 100644 --- a/consensus/polybft/signer/utils.go +++ b/consensus/polybft/signer/utils.go @@ -1,12 +1,14 @@ -package bls +package signer import ( "bytes" - "crypto/rand" "math/big" - "github.com/0xPolygon/polygon-edge/types" "github.com/umbracle/ethgo/abi" + + "github.com/0xPolygon/polygon-edge/bls" + "github.com/0xPolygon/polygon-edge/crypto" + "github.com/0xPolygon/polygon-edge/types" ) var ( @@ -14,51 +16,27 @@ var ( uint256ABIType = abi.MustNewType("uint256") ) -// GenerateBlsKey creates a random private and its corresponding public keys -func GenerateBlsKey() (*PrivateKey, error) { - s, err := randomK(rand.Reader) - if err != nil { - return nil, err - } - - return &PrivateKey{s: s}, nil -} - -// CreateRandomBlsKeys creates an array of random private and their corresponding public keys -func CreateRandomBlsKeys(total int) ([]*PrivateKey, error) { - blsKeys := make([]*PrivateKey, total) - - for i := 0; i < total; i++ { - blsKey, err := GenerateBlsKey() - if err != nil { - return nil, err - } - - blsKeys[i] = blsKey - } - - return blsKeys, nil -} +const ( + DomainValidatorSetString = "DOMAIN_CHILD_VALIDATOR_SET" + DomainCheckpointManagerString = "DOMAIN_CHECKPOINT_MANAGER" + DomainCommonSigningString = "DOMAIN_COMMON_SIGNING" + DomainStateReceiverString = "DOMAIN_STATE_RECEIVER" +) -// MarshalMessageToBigInt marshalls message into two big ints -// first we must convert message bytes to point and than for each coordinate we create big int -func MarshalMessageToBigInt(message, domain []byte) ([2]*big.Int, error) { - point, err := hashToPoint(message, domain) - if err != nil { - return [2]*big.Int{}, err - } +var ( + // domain used to map hash to G1 used by (child) validator set + DomainValidatorSet = crypto.Keccak256([]byte(DomainValidatorSetString)) - buf := point.Marshal() + // domain used to map hash to G1 used by child checkpoint manager + DomainCheckpointManager = crypto.Keccak256([]byte(DomainCheckpointManagerString)) - return [2]*big.Int{ - new(big.Int).SetBytes(buf[0:32]), - new(big.Int).SetBytes(buf[32:64]), - }, nil -} + DomainCommonSigning = crypto.Keccak256([]byte(DomainCommonSigningString)) + DomainStateReceiver = crypto.Keccak256([]byte(DomainStateReceiverString)) +) // MakeKOSKSignature creates KOSK signature which prevents rogue attack -func MakeKOSKSignature(privateKey *PrivateKey, address types.Address, - chainID int64, domain []byte, supernetManagerAddr types.Address) (*Signature, error) { +func MakeKOSKSignature(privateKey *bls.PrivateKey, address types.Address, + chainID int64, domain []byte, supernetManagerAddr types.Address) (*bls.Signature, error) { spenderABI, err := addressABIType.Encode(address) if err != nil { return nil, err diff --git a/consensus/polybft/signer/utils_test.go b/consensus/polybft/signer/utils_test.go index 56646de1ea..6e1a4ae575 100644 --- a/consensus/polybft/signer/utils_test.go +++ b/consensus/polybft/signer/utils_test.go @@ -1,81 +1,22 @@ -package bls +package signer import ( "encoding/hex" "testing" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func Test_SingleSign(t *testing.T) { - t.Parallel() - - validTestMsg, invalidTestMsg := testGenRandomBytes(t, messageSize), testGenRandomBytes(t, messageSize) - - blsKey, err := GenerateBlsKey() // structure which holds private/public key pair - require.NoError(t, err) - - // Sign valid message - signature, err := blsKey.Sign(validTestMsg, DomainValidatorSet) - require.NoError(t, err) - - isOk := signature.Verify(blsKey.PublicKey(), validTestMsg, DomainValidatorSet) - assert.True(t, isOk) - - // Verify if invalid message is signed with correct private key. Only use public key for the verification - // this should fail => isOk = false - isOk = signature.Verify(blsKey.PublicKey(), invalidTestMsg, DomainValidatorSet) - assert.False(t, isOk) -} - -func Test_AggregatedSign(t *testing.T) { - t.Parallel() - - validTestMsg, invalidTestMsg := testGenRandomBytes(t, messageSize), testGenRandomBytes(t, messageSize) - - keys, err := CreateRandomBlsKeys(participantsNumber) // create keys for validators - require.NoError(t, err) - - pubKeys := make([]*PublicKey, len(keys)) - - for i, key := range keys { - pubKeys[i] = key.PublicKey() - } - - var isOk bool - - signatures := Signatures{} - - // test all signatures at once - for i := 0; i < len(keys); i++ { - sign, err := keys[i].Sign(validTestMsg, DomainValidatorSet) - require.NoError(t, err) - - signatures = append(signatures, sign) - - // verify correctness of AggregateSignature - aggSig := signatures.Aggregate() - - isOk = aggSig.VerifyAggregated(pubKeys[:i+1], validTestMsg, DomainValidatorSet) - assert.True(t, isOk) - - isOk = aggSig.VerifyAggregated(pubKeys[:i+1], invalidTestMsg, DomainValidatorSet) - assert.False(t, isOk) - - isOk = aggSig.VerifyAggregated(pubKeys[:i+1], validTestMsg, DomainCheckpointManager) - assert.False(t, isOk) - } -} - func Test_MakeKOSKSignature(t *testing.T) { t.Parallel() expected := "03441ebc4bbca37664455b293cfc371ccf9a4f21e40c19a3a25beee77bf6e97d16cdd264c188a01d415ee99865f52567a402044a1c13aa6915a1237a41d35e9e" bytes, _ := hex.DecodeString("3139343634393730313533353434353137333331343333303931343932303731313035313730303336303738373134363131303435323837383335373237343933383834303135343336383231") - pk, err := UnmarshalPrivateKey(bytes) + pk, err := bls.UnmarshalPrivateKey(bytes) require.NoError(t, err) supernetManagerAddr := types.StringToAddress("0x1010101") diff --git a/consensus/polybft/stake_manager.go b/consensus/polybft/stake_manager.go index 046c9e7924..d91e80e71b 100644 --- a/consensus/polybft/stake_manager.go +++ b/consensus/polybft/stake_manager.go @@ -9,9 +9,9 @@ import ( "sort" "strings" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/helper/hex" "github.com/0xPolygon/polygon-edge/txrelayer" diff --git a/consensus/polybft/state_store_epoch_test.go b/consensus/polybft/state_store_epoch_test.go index 51cd3ef5a4..f9d8d8821a 100644 --- a/consensus/polybft/state_store_epoch_test.go +++ b/consensus/polybft/state_store_epoch_test.go @@ -5,7 +5,7 @@ import ( "sync" "testing" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/assert" diff --git a/consensus/polybft/state_sync_manager.go b/consensus/polybft/state_sync_manager.go index d29680a4f4..89a2b20dd9 100644 --- a/consensus/polybft/state_sync_manager.go +++ b/consensus/polybft/state_sync_manager.go @@ -10,20 +10,22 @@ import ( "sync" "time" + "github.com/hashicorp/go-hclog" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/umbracle/ethgo" + bolt "go.etcd.io/bbolt" + "google.golang.org/protobuf/proto" + + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" polybftProto "github.com/0xPolygon/polygon-edge/consensus/polybft/proto" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/contracts" "github.com/0xPolygon/polygon-edge/tracker" "github.com/0xPolygon/polygon-edge/types" - "github.com/hashicorp/go-hclog" - "github.com/libp2p/go-libp2p/core/peer" - "github.com/umbracle/ethgo" - bolt "go.etcd.io/bbolt" - "google.golang.org/protobuf/proto" ) type Runtime interface { @@ -228,20 +230,20 @@ func (s *stateSyncManager) saveVote(msg *TransportMessage) error { } // Verifies signature of the message against the public key of the signer and checks if the signer is a validator -func (s *stateSyncManager) verifyVoteSignature(valSet validator.ValidatorSet, signer types.Address, signature []byte, - hash []byte) error { - validator := valSet.Accounts().GetValidatorMetadata(signer) +func (s *stateSyncManager) verifyVoteSignature(valSet validator.ValidatorSet, signerAddr types.Address, + signature []byte, hash []byte) error { + validator := valSet.Accounts().GetValidatorMetadata(signerAddr) if validator == nil { - return fmt.Errorf("unable to resolve validator %s", signer) + return fmt.Errorf("unable to resolve validator %s", signerAddr) } unmarshaledSignature, err := bls.UnmarshalSignature(signature) if err != nil { - return fmt.Errorf("failed to unmarshal signature from signer %s, %w", signer.String(), err) + return fmt.Errorf("failed to unmarshal signature from signer %s, %w", signerAddr.String(), err) } - if !unmarshaledSignature.Verify(validator.BlsKey, hash, bls.DomainStateReceiver) { - return fmt.Errorf("incorrect signature from %s", signer) + if !unmarshaledSignature.Verify(validator.BlsKey, hash, signer.DomainStateReceiver) { + return fmt.Errorf("incorrect signature from %s", signerAddr) } return nil @@ -565,7 +567,7 @@ func (s *stateSyncManager) buildCommitment(dbTx *bolt.Tx) error { hashBytes := hash.Bytes() - signature, err := s.config.key.SignWithDomain(hashBytes, bls.DomainStateReceiver) + signature, err := s.config.key.SignWithDomain(hashBytes, signer.DomainStateReceiver) if err != nil { return fmt.Errorf("failed to sign commitment message. Error: %w", err) } diff --git a/consensus/polybft/state_sync_manager_test.go b/consensus/polybft/state_sync_manager_test.go index 4748f074ac..67a8a0fa43 100644 --- a/consensus/polybft/state_sync_manager_test.go +++ b/consensus/polybft/state_sync_manager_test.go @@ -16,7 +16,7 @@ import ( "google.golang.org/protobuf/proto" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/contracts" "github.com/0xPolygon/polygon-edge/helper/common" @@ -138,7 +138,7 @@ func TestStateSyncManager_MessagePool(t *testing.T) { s.validatorSet = vals.ToValidatorSet() badVal := validator.NewTestValidator(t, "a", 0) - msg, err := newMockMsg().sign(badVal, bls.DomainStateReceiver) + msg, err := newMockMsg().sign(badVal, signer.DomainStateReceiver) require.NoError(t, err) require.Error(t, s.saveVote(msg)) @@ -151,7 +151,7 @@ func TestStateSyncManager_MessagePool(t *testing.T) { s.validatorSet = vals.ToValidatorSet() val := newMockMsg() - msg, err := val.sign(vals.GetValidator("0"), bls.DomainStateReceiver) + msg, err := val.sign(vals.GetValidator("0"), signer.DomainStateReceiver) require.NoError(t, err) msg.EpochNumber = 1 @@ -176,7 +176,7 @@ func TestStateSyncManager_MessagePool(t *testing.T) { // validator signs the msg in behalf of another validator val := newMockMsg() - msg, err := val.sign(vals.GetValidator("0"), bls.DomainStateReceiver) + msg, err := val.sign(vals.GetValidator("0"), signer.DomainStateReceiver) require.NoError(t, err) msg.From = vals.GetValidator("1").Address().String() @@ -184,7 +184,7 @@ func TestStateSyncManager_MessagePool(t *testing.T) { // non validator signs the msg in behalf of a validator badVal := validator.NewTestValidator(t, "a", 0) - msg, err = newMockMsg().sign(badVal, bls.DomainStateReceiver) + msg, err = newMockMsg().sign(badVal, signer.DomainStateReceiver) require.NoError(t, err) msg.From = vals.GetValidator("1").Address().String() @@ -198,10 +198,10 @@ func TestStateSyncManager_MessagePool(t *testing.T) { s.validatorSet = vals.ToValidatorSet() msg := newMockMsg() - val1signed, err := msg.sign(vals.GetValidator("1"), bls.DomainStateReceiver) + val1signed, err := msg.sign(vals.GetValidator("1"), signer.DomainStateReceiver) require.NoError(t, err) - val2signed, err := msg.sign(vals.GetValidator("2"), bls.DomainStateReceiver) + val2signed, err := msg.sign(vals.GetValidator("2"), signer.DomainStateReceiver) require.NoError(t, err) // vote with validator 1 @@ -255,10 +255,10 @@ func TestStateSyncManager_BuildCommitment(t *testing.T) { // validators 0 and 1 vote for the proposal, there is not enough // voting power for the proposal - signedMsg1, err := msg.sign(vals.GetValidator("0"), bls.DomainStateReceiver) + signedMsg1, err := msg.sign(vals.GetValidator("0"), signer.DomainStateReceiver) require.NoError(t, err) - signedMsg2, err := msg.sign(vals.GetValidator("1"), bls.DomainStateReceiver) + signedMsg2, err := msg.sign(vals.GetValidator("1"), signer.DomainStateReceiver) require.NoError(t, err) require.NoError(t, s.saveVote(signedMsg1)) @@ -270,10 +270,10 @@ func TestStateSyncManager_BuildCommitment(t *testing.T) { // validator 2 and 3 vote for the proposal, there is enough voting power now - signedMsg1, err = msg.sign(vals.GetValidator("2"), bls.DomainStateReceiver) + signedMsg1, err = msg.sign(vals.GetValidator("2"), signer.DomainStateReceiver) require.NoError(t, err) - signedMsg2, err = msg.sign(vals.GetValidator("3"), bls.DomainStateReceiver) + signedMsg2, err = msg.sign(vals.GetValidator("3"), signer.DomainStateReceiver) require.NoError(t, err) require.NoError(t, s.saveVote(signedMsg1)) diff --git a/consensus/polybft/validator/genesis_validator.go b/consensus/polybft/validator/genesis_validator.go index 671897e31a..d2eb5268c6 100644 --- a/consensus/polybft/validator/genesis_validator.go +++ b/consensus/polybft/validator/genesis_validator.go @@ -6,7 +6,7 @@ import ( "fmt" "math/big" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/types" ) diff --git a/consensus/polybft/validator/test_helpers.go b/consensus/polybft/validator/test_helpers.go index 4bc943f955..a1878b4567 100644 --- a/consensus/polybft/validator/test_helpers.go +++ b/consensus/polybft/validator/test_helpers.go @@ -8,8 +8,8 @@ import ( "strconv" "testing" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/types" "github.com/hashicorp/go-hclog" diff --git a/consensus/polybft/validator/validator_metadata.go b/consensus/polybft/validator/validator_metadata.go index 8baf12f8f9..c21f6408d6 100644 --- a/consensus/polybft/validator/validator_metadata.go +++ b/consensus/polybft/validator/validator_metadata.go @@ -9,8 +9,8 @@ import ( "math/big" "reflect" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" diff --git a/consensus/polybft/validator/validator_metadata_test.go b/consensus/polybft/validator/validator_metadata_test.go index e6999a87f6..fcdcb71495 100644 --- a/consensus/polybft/validator/validator_metadata_test.go +++ b/consensus/polybft/validator/validator_metadata_test.go @@ -5,8 +5,8 @@ import ( "math/big" "testing" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/consensus/polybft/validator/validator_set_delta_test.go b/consensus/polybft/validator/validator_set_delta_test.go index ca1911dc45..3e0af84775 100644 --- a/consensus/polybft/validator/validator_set_delta_test.go +++ b/consensus/polybft/validator/validator_set_delta_test.go @@ -5,7 +5,7 @@ import ( "math/big" "testing" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/bls" "github.com/stretchr/testify/require" "github.com/umbracle/fastrlp" ) diff --git a/consensus/polybft/wallet/account.go b/consensus/polybft/wallet/account.go index b6c8600221..992da93e62 100644 --- a/consensus/polybft/wallet/account.go +++ b/consensus/polybft/wallet/account.go @@ -5,7 +5,7 @@ import ( "encoding/hex" "fmt" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/secrets" "github.com/0xPolygon/polygon-edge/types" "github.com/umbracle/ethgo/wallet" diff --git a/consensus/polybft/wallet/key.go b/consensus/polybft/wallet/key.go index a0a27f79c2..fcf7ad9353 100644 --- a/consensus/polybft/wallet/key.go +++ b/consensus/polybft/wallet/key.go @@ -4,11 +4,12 @@ import ( "fmt" "github.com/0xPolygon/go-ibft/messages/proto" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" - "github.com/0xPolygon/polygon-edge/crypto" - "github.com/0xPolygon/polygon-edge/types" "github.com/umbracle/ethgo" protobuf "google.golang.org/protobuf/proto" + + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/crypto" + "github.com/0xPolygon/polygon-edge/types" ) type Key struct { @@ -34,7 +35,7 @@ func (k *Key) Address() ethgo.Address { // Sign signs the provided digest with BLS key // Used only to sign transactions func (k *Key) Sign(digest []byte) ([]byte, error) { - return k.SignWithDomain(digest, bls.DomainCommonSigning) + return k.SignWithDomain(digest, signer.DomainCommonSigning) } // SignWithDomain signs the provided digest with BLS key and provided domain diff --git a/consensus/polybft/wallet/key_test.go b/consensus/polybft/wallet/key_test.go index c1547dbe13..9e0625c6e4 100644 --- a/consensus/polybft/wallet/key_test.go +++ b/consensus/polybft/wallet/key_test.go @@ -4,9 +4,10 @@ import ( "testing" "github.com/0xPolygon/go-ibft/messages/proto" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/0xPolygon/polygon-edge/bls" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" ) func Test_RecoverAddressFromSignature(t *testing.T) { @@ -28,7 +29,7 @@ func Test_RecoverAddressFromSignature(t *testing.T) { address, err := RecoverAddressFromSignature(msg.Signature, payload) require.NoError(t, err) - assert.Equal(t, key.Address().Bytes(), address.Bytes()) + require.Equal(t, key.Address().Bytes(), address.Bytes()) } } @@ -39,14 +40,14 @@ func Test_Sign(t *testing.T) { for _, account := range []*Account{generateTestAccount(t), generateTestAccount(t)} { key := NewKey(account) - ser, err := key.SignWithDomain(msg, bls.DomainCheckpointManager) + ser, err := key.SignWithDomain(msg, signer.DomainCheckpointManager) require.NoError(t, err) sig, err := bls.UnmarshalSignature(ser) require.NoError(t, err) - assert.True(t, sig.Verify(key.raw.Bls.PublicKey(), msg, bls.DomainCheckpointManager)) + require.True(t, sig.Verify(key.raw.Bls.PublicKey(), msg, signer.DomainCheckpointManager)) } } @@ -55,6 +56,6 @@ func Test_String(t *testing.T) { for _, account := range []*Account{generateTestAccount(t), generateTestAccount(t), generateTestAccount(t)} { key := NewKey(account) - assert.Equal(t, key.Address().String(), key.String()) + require.Equal(t, key.Address().String(), key.String()) } } diff --git a/e2e/framework/testserver.go b/e2e/framework/testserver.go index fde06aa48d..13cff2db5c 100644 --- a/e2e/framework/testserver.go +++ b/e2e/framework/testserver.go @@ -244,13 +244,13 @@ func (t *TestServer) SecretsInit() (*InitIBFTResult, error) { if t.Config.ValidatorType == validators.BLSValidatorType { // Generate the BLS Key - _, bksKeyEncoded, keyErr := crypto.GenerateAndEncodeBLSSecretKey() + _, blsKeyEncoded, keyErr := crypto.GenerateAndEncodeBLSSecretKey() if keyErr != nil { return nil, keyErr } // Write the networking private key to the secrets manager storage - if setErr := localSecretsManager.SetSecret(secrets.ValidatorBLSKey, bksKeyEncoded); setErr != nil { + if setErr := localSecretsManager.SetSecret(secrets.ValidatorBLSKey, blsKeyEncoded); setErr != nil { return nil, setErr } } diff --git a/state/runtime/precompiled/bls_agg_sigs_verification.go b/state/runtime/precompiled/bls_agg_sigs_verification.go index bbed7a14ae..06e21cfc61 100644 --- a/state/runtime/precompiled/bls_agg_sigs_verification.go +++ b/state/runtime/precompiled/bls_agg_sigs_verification.go @@ -3,8 +3,9 @@ package precompiled import ( "errors" + "github.com/0xPolygon/polygon-edge/bls" "github.com/0xPolygon/polygon-edge/chain" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/state/runtime" "github.com/0xPolygon/polygon-edge/types" "github.com/umbracle/ethgo/abi" @@ -99,7 +100,7 @@ func (c *blsAggSignsVerification) run(input []byte, caller types.Address, host r blsPubKeys[i] = blsPubKey } - if sig.VerifyAggregated(blsPubKeys, types.Hash(msg).Bytes(), bls.DomainStateReceiver) { + if sig.VerifyAggregated(blsPubKeys, types.Hash(msg).Bytes(), signer.DomainStateReceiver) { return abiBoolTrue, nil } diff --git a/state/runtime/precompiled/bls_agg_sigs_verification_test.go b/state/runtime/precompiled/bls_agg_sigs_verification_test.go index 6a3afcfbae..08cff7293d 100644 --- a/state/runtime/precompiled/bls_agg_sigs_verification_test.go +++ b/state/runtime/precompiled/bls_agg_sigs_verification_test.go @@ -3,7 +3,8 @@ package precompiled import ( "testing" - bls "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/bls" + "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -67,7 +68,7 @@ func generatePubKeysAndSignature(t *testing.T, numKeys int, messageRaw []byte) ( signatures := make(bls.Signatures, len(validators)) for i, validator := range validators { - sign, err := validator.Sign(message[:], bls.DomainStateReceiver) + sign, err := validator.Sign(message[:], signer.DomainStateReceiver) require.NoError(t, err) pubKeys[i] = validator.PublicKey().Marshal()