Skip to content

Commit

Permalink
Merge branch 'develop' into feat/decouple-from-ethgo-tx-signing-logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan-Ethernal committed Mar 20, 2024
2 parents 870d51c + e6f539c commit ed3eb62
Show file tree
Hide file tree
Showing 33 changed files with 1,317 additions and 335 deletions.
24 changes: 0 additions & 24 deletions consensus/polybft/checkpoint_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,11 @@ import (
"strconv"
"testing"

"github.com/umbracle/ethgo/abi"
"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/crypto"
"github.com/0xPolygon/polygon-edge/helper/common"
merkle "github.com/Ethernal-Tech/merkle-tree"
hclog "github.com/hashicorp/go-hclog"
"github.com/stretchr/testify/mock"
Expand Down Expand Up @@ -510,24 +507,3 @@ func getBlockNumberCheckpointSubmitInput(t *testing.T, input []byte) uint64 {

return submit.Checkpoint.BlockNumber.Uint64()
}

func createTestLogForExitEvent(t *testing.T, exitEventID uint64) *types.Log {
t.Helper()

var exitEvent contractsapi.L2StateSyncedEvent

topics := make([]types.Hash, 4)
topics[0] = types.Hash(exitEvent.Sig())
topics[1] = types.BytesToHash(common.EncodeUint64ToBytes(exitEventID))
topics[2] = types.BytesToHash(types.StringToAddress("0x1111").Bytes())
topics[3] = types.BytesToHash(types.StringToAddress("0x2222").Bytes())
someType := abi.MustNewType("tuple(string firstName, string lastName)")
encodedData, err := someType.Encode(map[string]string{"firstName": "John", "lastName": "Doe"})
require.NoError(t, err)

return &types.Log{
Address: contracts.L2StateSenderContract,
Topics: topics,
Data: encodedData,
}
}
15 changes: 0 additions & 15 deletions consensus/polybft/consensus_runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -1069,18 +1069,3 @@ func (c *consensusRuntime) getCurrentBlockTimeDrift() uint64 {

return c.epoch.CurrentClientConfig.BlockTimeDrift
}

// getSealersForBlock checks who sealed a given block and updates the counter
func getSealersForBlock(sealersCounter map[types.Address]uint64,
blockExtra *Extra, validators validator.AccountSet) error {
signers, err := validators.GetFilteredValidators(blockExtra.Parent.Bitmap)
if err != nil {
return err
}

for _, a := range signers.GetAddresses() {
sealersCounter[a]++
}

return nil
}
21 changes: 0 additions & 21 deletions consensus/polybft/governance_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@ import (

"github.com/0xPolygon/polygon-edge/chain"
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi"
"github.com/0xPolygon/polygon-edge/contracts"
"github.com/0xPolygon/polygon-edge/forkmanager"
"github.com/0xPolygon/polygon-edge/types"
"github.com/hashicorp/go-hclog"
"github.com/stretchr/testify/require"
"github.com/umbracle/ethgo/abi"
)

func TestGovernanceManager_PostEpoch(t *testing.T) {
Expand Down Expand Up @@ -143,22 +141,3 @@ func TestGovernanceManager_PostBlock(t *testing.T) {
require.True(t, forkmanager.GetInstance().IsForkEnabled(newForkName, newForkBlock.Uint64()))
})
}

func createTestLogForNewEpochSizeEvent(t *testing.T, epochSize uint64) *types.Log {
t.Helper()

var epochSizeEvent contractsapi.NewEpochSizeEvent

topics := make([]types.Hash, 2)
topics[0] = types.Hash(epochSizeEvent.Sig())
encodedData, err := abi.MustNewType("uint256").Encode(new(big.Int).SetUint64(epochSize))
require.NoError(t, err)

topics[1] = types.BytesToHash(encodedData)

return &types.Log{
Address: contracts.NetworkParamsContract,
Topics: topics,
Data: nil,
}
}
2 changes: 1 addition & 1 deletion consensus/polybft/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func createTestKey(t *testing.T) *wallet.Key {
func createRandomTestKeys(t *testing.T, numberOfKeys int) []*wallet.Key {
t.Helper()

result := make([]*wallet.Key, numberOfKeys, numberOfKeys)
result := make([]*wallet.Key, numberOfKeys)

for i := 0; i < numberOfKeys; i++ {
result[i] = wallet.NewKey(generateTestAccount(t))
Expand Down
5 changes: 0 additions & 5 deletions consensus/polybft/polybft.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ package polybft
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/big"
"path/filepath"
Expand Down Expand Up @@ -35,10 +34,6 @@ const (
bridgeProto = "/bridge/0.2"
)

var (
errMissingBridgeConfig = errors.New("invalid genesis configuration, missing bridge configuration")
)

// polybftBackend is an interface defining polybft methods needed by fsm and sync tracker
type polybftBackend interface {
// GetValidators retrieves validator set for the given block
Expand Down
6 changes: 3 additions & 3 deletions consensus/polybft/sc_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,12 +276,12 @@ func TestIntegration_CommitEpoch(t *testing.T) {
reward := uint64(math.Pow(10, 18)) // 1 token
walletAddress := types.StringToAddress("1234889893")

validatorSets := make([]*validator.TestValidators, len(validatorSetSize), len(validatorSetSize))
validatorSets := make([]*validator.TestValidators, len(validatorSetSize))

// create all validator sets which will be used in test
for i, size := range validatorSetSize {
aliases := make([]string, size, size)
vps := make([]uint64, size, size)
aliases := make([]string, size)
vps := make([]uint64, size)

for j := 0; j < size; j++ {
aliases[j] = "v" + strconv.Itoa(j)
Expand Down
13 changes: 0 additions & 13 deletions consensus/polybft/stake_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/0xPolygon/polygon-edge/consensus/polybft/bitmap"
"github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi"
"github.com/0xPolygon/polygon-edge/consensus/polybft/validator"
"github.com/0xPolygon/polygon-edge/crypto"
"github.com/0xPolygon/polygon-edge/helper/hex"
"github.com/0xPolygon/polygon-edge/types"
"github.com/hashicorp/go-hclog"
Expand Down Expand Up @@ -68,11 +67,8 @@ var _ StakeManager = (*stakeManager)(nil)
type stakeManager struct {
logger hclog.Logger
state *State
key crypto.Key
stakeManagerContractAddr types.Address
validatorSetContract types.Address
polybftBackend polybftBackend
stakeManagerContract *contract.Contract
blockchain blockchainBackend
}

Expand Down Expand Up @@ -470,12 +466,3 @@ func (sc validatorStakeMap) String() string {

return sb.String()
}

func getEpochID(blockchain blockchainBackend, header *types.Header) (uint64, error) {
provider, err := blockchain.GetStateProviderForBlock(header)
if err != nil {
return 0, err
}

return blockchain.GetSystemState(provider).GetEpoch()
}
5 changes: 0 additions & 5 deletions consensus/polybft/stake_manager_fuzz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,6 @@ import (
"github.com/stretchr/testify/require"
)

type epochIDValidatorsF struct {
EpochID uint64
Validators []*validator.ValidatorMetadata
}

type postBlockStructF struct {
EpochID uint64
ValidatorID uint64
Expand Down
2 changes: 0 additions & 2 deletions consensus/polybft/state_event_getter.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ type EventProvider struct {

subscriberIDCounter uint64

blockchain blockchainBackend

subscribers map[uint64]EventSubscriber
allFilters map[types.Address]map[types.Hash][]uint64
}
Expand Down
5 changes: 1 addition & 4 deletions consensus/polybft/state_store_exit.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package polybft
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"sort"

Expand All @@ -19,8 +18,6 @@ var (
exitEventsBucket = []byte("exitEvent")
exitEventToEpochLookupBucket = []byte("exitIdToEpochLookup")
exitRelayerEventsBucket = []byte("exitRelayerEvents")

errNoLastSavedEntry = errors.New("there is no last saved block in last saved bucket")
)

type exitEventNotFoundError struct {
Expand Down Expand Up @@ -136,7 +133,7 @@ func getExitEventSingle(exitEventID uint64, tx *bolt.Tx) (*ExitEvent, error) {
key := bytes.Join([][]byte{epochBytes, exitIDBytes}, nil)
k, v := exitEventBucket.Cursor().Seek(key)

if bytes.HasPrefix(k, key) == false || v == nil {
if !bytes.HasPrefix(k, key) || v == nil {
return nil, &exitEventNotFoundError{
exitID: exitEventID,
epoch: common.EncodeBytesToUint64(epochBytes),
Expand Down
2 changes: 0 additions & 2 deletions consensus/polybft/state_store_state_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ var (

// errNotEnoughStateSyncs error message
errNotEnoughStateSyncs = errors.New("there is either a gap or not enough sync events")
// errCommitmentNotBuilt error message
errCommitmentNotBuilt = errors.New("there is no built commitment to register")
// errNoCommitmentForStateSync error message
errNoCommitmentForStateSync = errors.New("no commitment found for given state sync event")
)
Expand Down
5 changes: 0 additions & 5 deletions consensus/polybft/state_sync_commitment.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,6 @@ import (
merkle "github.com/Ethernal-Tech/merkle-tree"
)

const (
stTypeBridgeCommitment = "commitment"
stTypeEndEpoch = "end-epoch"
)

// PendingCommitment holds merkle trie of bridge transactions accompanied by epoch number
type PendingCommitment struct {
*contractsapi.StateSyncCommitment
Expand Down
1 change: 0 additions & 1 deletion consensus/polybft/state_sync_relayer.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
)

var (
errFailedToExecuteStateSync = errors.New("failed to execute state sync")
errUnknownStateSyncRelayerEvent = errors.New("unknown event from state receiver contract")

commitmentEventSignature = new(contractsapi.NewCommitmentEvent).Sig()
Expand Down
54 changes: 0 additions & 54 deletions consensus/polybft/stats.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
package polybft

import (
"math/big"
"time"

"github.com/0xPolygon/polygon-edge/txrelayer"
"github.com/armon/go-metrics"
"github.com/hashicorp/go-hclog"
"github.com/prometheus/client_golang/prometheus"
"github.com/umbracle/ethgo"
)

// startStatsReleasing starts the process that releases BoltDB stats into prometheus periodically.
Expand Down Expand Up @@ -158,53 +154,3 @@ func (s *State) startStatsReleasing() {
prev = stats
}
}

// publishRootchainMetrics publishes rootchain related metrics
func (p *Polybft) publishRootchainMetrics(logger hclog.Logger) {
interval := p.config.MetricsInterval
validatorAddr := ethgo.Address(p.key.Address())
bridgeCfg := p.genesisClientConfig.Bridge

// zero means metrics are disabled
if interval <= 0 {
return
}

relayer, err := txrelayer.NewTxRelayer(txrelayer.WithIPAddress(bridgeCfg.JSONRPCEndpoint))
if err != nil {
logger.Error("failed to connect to the rootchain node", "err", err, "JSON RPC", bridgeCfg.JSONRPCEndpoint)

return
}

gweiPerWei := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(9), nil)) // 10^9

ticker := time.NewTicker(interval)
defer ticker.Stop()

for {
select {
case <-p.closeCh:
return
case <-ticker.C:
// rootchain validator balance
balance, err := relayer.Client().Eth().GetBalance(validatorAddr, ethgo.Latest)
if err != nil {
logger.Error("failed to query eth_getBalance", "err", err)
} else {
balanceInGwei := new(big.Float).Quo(new(big.Float).SetInt(balance), gweiPerWei)
balanceInGweiFloat, _ := balanceInGwei.Float32()

metrics.SetGauge([]string{"bridge", "validator_root_balance_gwei", validatorAddr.String()}, balanceInGweiFloat)
}

// rootchain current checkpoint block
checkpointBlock, err := getCurrentCheckpointBlock(relayer, bridgeCfg.CheckpointManagerAddr)
if err != nil {
logger.Error("failed to query latest checkpoint block", "err", err)
} else {
metrics.SetGauge([]string{"bridge", "checkpoint_block_number"}, float32(checkpointBlock))
}
}
}
}
Loading

0 comments on commit ed3eb62

Please sign in to comment.