Skip to content

Commit

Permalink
feat: PR comment, checkPendingCertificatesStatus returns bool and error
Browse files Browse the repository at this point in the history
  • Loading branch information
joanestebanr committed Nov 12, 2024
1 parent 3cab2b3 commit bb7e5d4
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 32 deletions.
39 changes: 28 additions & 11 deletions aggsender/aggsender.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"math/big"
"os"
"slices"
"time"

"github.com/0xPolygon/cdk/agglayer"
Expand Down Expand Up @@ -92,9 +93,14 @@ func (a *AggSender) sendCertificates(ctx context.Context) {
select {
case epoch := <-chEpoch:
a.log.Infof("Epoch received: %s", epoch.String())
a.checkPendingCertificatesStatus(ctx)
if _, err := a.sendCertificate(ctx); err != nil {
log.Error(err)
thereArePendingCerts, err := a.checkPendingCertificatesStatus(ctx)
if err == nil && !thereArePendingCerts {
if _, err := a.sendCertificate(ctx); err != nil {
log.Error(err)
}
} else {
log.Warnf("Skipping epoch %s because there are pending certificates %v or error: %w",
epoch.String(), thereArePendingCerts, err)
}
case <-ctx.Done():
a.log.Info("AggSender stopped")
Expand Down Expand Up @@ -480,19 +486,28 @@ func (a *AggSender) signCertificate(certificate *agglayer.Certificate) (*agglaye

// checkPendingCertificatesStatus checks the status of pending certificates
// and updates in the storage if it changed on agglayer
func (a *AggSender) checkPendingCertificatesStatus(ctx context.Context) {
// It returns:
// bool -> if there are pending certificates
// error -> if there was an error
func (a *AggSender) checkPendingCertificatesStatus(ctx context.Context) (bool, error) {
pendingCertificates, err := a.storage.GetCertificatesByStatus(nonSettledStatuses)
if err != nil {
a.log.Errorf("error getting pending certificates: %w", err)
return
err = fmt.Errorf("error getting pending certificates: %w", err)
a.log.Error(err)
return true, err
}
thereArePendingCertificates := false
a.log.Debugf("checkPendingCertificatesStatus num of pendingCertificates: %d", len(pendingCertificates))
for _, certificate := range pendingCertificates {
certificateHeader, err := a.aggLayerClient.GetCertificateHeader(certificate.CertificateID)
if err != nil {
a.log.Errorf("error getting certificate header of %s from agglayer: %w",
certificate.String(), err)
continue
err = fmt.Errorf("error getting certificate header of %d/%s from agglayer: %w",
certificate.Height, certificate.String(), err)
a.log.Error(err)
return true, err
}
if slices.Contains(nonSettledStatuses, certificateHeader.Status) {
thereArePendingCertificates = true
}
a.log.Debugf("aggLayerClient.GetCertificateHeader status [%s] of certificate %s ",
certificateHeader.Status,
Expand All @@ -506,11 +521,13 @@ func (a *AggSender) checkPendingCertificatesStatus(ctx context.Context) {
certificate.UpdatedAt = time.Now().UTC().UnixMilli()

if err := a.storage.UpdateCertificateStatus(ctx, *certificate); err != nil {
a.log.Errorf("error updating certificate %s status in storage: %w", certificateHeader.String(), err)
continue
err = fmt.Errorf("error updating certificate %s status in storage: %w", certificateHeader.String(), err)
a.log.Error(err)
return true, err
}
}
}
return thereArePendingCertificates, nil
}

// shouldSendCertificate checks if a certificate should be sent at given time
Expand Down
33 changes: 19 additions & 14 deletions aggsender/aggsender_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -750,17 +750,17 @@ func generateTestProof(t *testing.T) treeTypes.Proof {
}

func TestCheckIfCertificatesAreSettled(t *testing.T) {
t.Parallel()

tests := []struct {
name string
pendingCertificates []*aggsendertypes.CertificateInfo
certificateHeaders map[common.Hash]*agglayer.CertificateHeader
getFromDBError error
clientError error
updateDBError error
expectedErrorLogMessages []string
expectedInfoMessages []string
name string
pendingCertificates []*aggsendertypes.CertificateInfo
certificateHeaders map[common.Hash]*agglayer.CertificateHeader
getFromDBError error
clientError error
updateDBError error
expectedErrorLogMessages []string
expectedInfoMessages []string
expectedThereArePendingCerts bool
expectedError bool
}{
{
name: "All certificates settled - update successful",
Expand Down Expand Up @@ -796,6 +796,8 @@ func TestCheckIfCertificatesAreSettled(t *testing.T) {
expectedErrorLogMessages: []string{
"error getting pending certificates: %w",
},
expectedThereArePendingCerts: true,
expectedError: true,
},
{
name: "Error getting certificate header",
Expand All @@ -809,6 +811,8 @@ func TestCheckIfCertificatesAreSettled(t *testing.T) {
expectedErrorLogMessages: []string{
"error getting header of certificate %s with height: %d from agglayer: %w",
},
expectedThereArePendingCerts: true,
expectedError: true,
},
{
name: "Error updating certificate status",
Expand All @@ -825,15 +829,15 @@ func TestCheckIfCertificatesAreSettled(t *testing.T) {
expectedInfoMessages: []string{
"certificate %s changed status to %s",
},
expectedThereArePendingCerts: true,
expectedError: true,
},
}

for _, tt := range tests {
tt := tt

t.Run(tt.name, func(t *testing.T) {
t.Parallel()

mockStorage := mocks.NewAggSenderStorage(t)
mockAggLayerClient := agglayer.NewAgglayerClientMock(t)
mockLogger := log.WithFields("test", "unittest")
Expand All @@ -860,8 +864,9 @@ func TestCheckIfCertificatesAreSettled(t *testing.T) {
}

ctx := context.TODO()
aggSender.checkPendingCertificatesStatus(ctx)

thereArePendingCerts, err := aggSender.checkPendingCertificatesStatus(ctx)
require.Equal(t, tt.expectedThereArePendingCerts, thereArePendingCerts)
require.Equal(t, tt.expectedError, err != nil)
mockAggLayerClient.AssertExpectations(t)
mockStorage.AssertExpectations(t)
})
Expand Down
2 changes: 1 addition & 1 deletion aggsender/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type Config struct {
BlockFinality string `jsonschema:"enum=LatestBlock, enum=SafeBlock, enum=PendingBlock, enum=FinalizedBlock, enum=EarliestBlock" mapstructure:"BlockFinality"` //nolint:lll
// EpochNotificationPercentage indicates the percentage of the epoch
// the AggSender should send the certificate
// 0 -> Begining
// 0 -> Begin
// 50 -> Middle
EpochNotificationPercentage uint `mapstructure:"EpochNotificationPercentage"`
// SaveCertificatesToFilesPath if != "" tells the AggSender to save the certificates to a file in this path
Expand Down
12 changes: 8 additions & 4 deletions aggsender/epoch_notifier_per_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import (
"github.com/0xPolygon/cdk/aggsender/types"
)

const (
maxPercent = 100.0
)

type ExtraInfoEventEpoch struct {
PendingBlocks int
}
Expand All @@ -21,7 +25,7 @@ type ConfigEpochNotifierPerBlock struct {
NumBlockPerEpoch uint

// EpochNotificationPercentage
// 0 -> begining new Epoch
// 0 -> begin new Epoch
// 50 -> middle of epoch
// 100 -> end of epoch (same as 0)
EpochNotificationPercentage uint
Expand All @@ -47,7 +51,7 @@ func (c *ConfigEpochNotifierPerBlock) Validate() error {
if c.NumBlockPerEpoch == 0 {
return fmt.Errorf("numBlockPerEpoch: num block per epoch is required > 0 ")
}
if c.EpochNotificationPercentage >= 100 {
if c.EpochNotificationPercentage >= maxPercent {
return fmt.Errorf("epochNotificationPercentage: must be between 0 and 99")
}
return nil
Expand Down Expand Up @@ -169,13 +173,13 @@ func (e *EpochNotifierPerBlock) percentEpoch(currentBlock uint64) float64 {
}
func (e *EpochNotifierPerBlock) isNotificationRequired(currentBlock, lastEpochNotified uint64) (bool, uint64) {
percentEpoch := e.percentEpoch(currentBlock)
thresholdPercent := float64(e.Config.EpochNotificationPercentage) / 100.0
thresholdPercent := float64(e.Config.EpochNotificationPercentage) / maxPercent
maxTresholdPercent := float64(e.Config.NumBlockPerEpoch-1) / float64(e.Config.NumBlockPerEpoch)
if thresholdPercent > maxTresholdPercent {
thresholdPercent = maxTresholdPercent
}
if percentEpoch < thresholdPercent {
e.logger.Debugf("Block %d is at %f%% of the epoch no notify", currentBlock, percentEpoch*100)
e.logger.Debugf("Block %d is at %f%% of the epoch no notify", currentBlock, percentEpoch*maxPercent)
return false, e.epochNumber(currentBlock)
}
nextEpoch := e.epochNumber(currentBlock) + 1
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ require (
go.uber.org/zap v1.27.0
golang.org/x/crypto v0.27.0
golang.org/x/net v0.29.0
golang.org/x/sync v0.8.0
golang.org/x/sync v0.9.0
google.golang.org/grpc v1.64.0
google.golang.org/protobuf v1.34.2
modernc.org/sqlite v1.32.0
Expand Down Expand Up @@ -151,7 +151,7 @@ require (
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
go.opentelemetry.io/otel/trace v1.24.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa // indirect
golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f // indirect
golang.org/x/sys v0.25.0 // indirect
golang.org/x/text v0.18.0 // indirect
golang.org/x/time v0.5.0 // indirect
Expand Down
7 changes: 7 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ github.com/0xPolygon/cdk-rpc v0.0.0-20241004114257-6c3cb6eebfb6 h1:FXL/rcO7/GtZ3
github.com/0xPolygon/cdk-rpc v0.0.0-20241004114257-6c3cb6eebfb6/go.mod h1:2scWqMMufrQXu7TikDgQ3BsyaKoX8qP26D6E262vSOg=
github.com/0xPolygon/zkevm-ethtx-manager v0.2.1 h1:2Yb+KdJFMpVrS9LIkd658XiWuN+MCTs7SgeWaopXScg=
github.com/0xPolygon/zkevm-ethtx-manager v0.2.1/go.mod h1:lqQmzSo2OXEZItD0R4Cd+lqKFxphXEWgqHefVcGDZZc=
github.com/0xPolygonHermez/zkevm-data-streamer v0.2.7/go.mod h1:7nM7Ihk+fTG1TQPwdZoGOYd3wprqqyIyjtS514uHzWE=
github.com/0xPolygonHermez/zkevm-synchronizer-l1 v1.0.5 h1:YmnhuCl349MoNASN0fMeGKU1o9HqJhiZkfMsA/1cTRA=
github.com/0xPolygonHermez/zkevm-synchronizer-l1 v1.0.5/go.mod h1:X4Su/M/+hSISqdl9yomKlRsbTyuZHsRohporyHsP8gg=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
Expand Down Expand Up @@ -482,13 +483,16 @@ golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=
golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70=
golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa h1:FRnLl4eNAQl8hwxVVC17teOw8kdjVDVAiFMtgUdTSRQ=
golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE=
golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f h1:XdNn9LlyWAhLVp6P/i8QYBW+hlyhrhei9uErw2B5GJo=
golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f/go.mod h1:D5SMRVC3C2/4+F/DB1wZsLRnSNimn2Sp/NPsCrsv8ak=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
Expand All @@ -510,6 +514,8 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ=
golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
Expand Down Expand Up @@ -571,6 +577,7 @@ golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4f
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
golang.org/x/tools v0.27.0 h1:qEKojBykQkQ4EynWy4S8Weg69NumxKdn40Fce3uc/8o=
golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
Expand Down

0 comments on commit bb7e5d4

Please sign in to comment.