Skip to content

Commit

Permalink
fixup! feat(evm-reader): Read claim acceptance
Browse files Browse the repository at this point in the history
  • Loading branch information
fmoura committed Sep 7, 2024
1 parent 02633eb commit 0e09f60
Show file tree
Hide file tree
Showing 4 changed files with 165 additions and 34 deletions.
16 changes: 10 additions & 6 deletions internal/evmreader/claim.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,13 @@ func (r *EvmReader) readAndUpdateClaims(

appAddresses := appsToAddresses(apps)

// All these apps shares the same IConsensus
// All apps shares the same IConsensus
// If there is a key on indexApps, there is at least one
// application in the referred application slice
consensusContract := apps[0].consensusContract

// Retrieve Claim Acceptance Events from blockchain
appClaimAcceptanceEventMap, err := r.readClaimAcceptanceFromBlockchain(
appClaimAcceptanceEventMap, err := r.readClaimsAcceptance(
ctx, consensusContract, appAddresses, lastClaimCheck+1, mostRecentBlockNumber)
if err != nil {
slog.Error("Error reading claim acceptance status",
Expand All @@ -109,10 +109,11 @@ func (r *EvmReader) readAndUpdateClaims(
ctx, app, claimAcceptance.LastProcessedBlockNumber.Uint64())
if err != nil {
slog.Error("Error retrieving previous submitted claims",
"app", app, "error", err)
"app", app,
"block", claimAcceptance.LastProcessedBlockNumber.Uint64(),
"error", err)
continue APP_LOOP
}

if len(previousEpochs) > 0 {
slog.Error("Application got 'not accepted' claims. It is in an invalid state",
"app", app)
Expand All @@ -126,7 +127,10 @@ func (r *EvmReader) readAndUpdateClaims(
claimAcceptance.LastProcessedBlockNumber.Uint64()),
app)
if err != nil {
slog.Error("Error retrieving Epoch", "app", app, "error", err)
slog.Error("Error retrieving Epoch",
"app", app,
"block", claimAcceptance.LastProcessedBlockNumber.Uint64(),
"error", err)
continue APP_LOOP
}

Expand Down Expand Up @@ -170,7 +174,7 @@ func (r *EvmReader) readAndUpdateClaims(
}
}

func (r *EvmReader) readClaimAcceptanceFromBlockchain(
func (r *EvmReader) readClaimsAcceptance(
ctx context.Context,
consensusContract ConsensusContract,
appAddresses []common.Address,
Expand Down
166 changes: 145 additions & 21 deletions internal/evmreader/claim_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,18 +206,8 @@ func (s *EvmReaderSuite) TestReadClaimAcceptance() {
LastClaimCheckBlock: 0x11,
}}, nil).Once()

claim0Hash := common.HexToHash("0xdeadbeef")
claim0 := &Epoch{
Index: 1,
FirstBlock: 1,
LastBlock: 1,
AppAddress: appAddress,
Status: EpochStatusClaimSubmitted,
ClaimHash: &claim0Hash,
}

claim1Hash := common.HexToHash("0xdeadbeef")
claim1 := &Epoch{
claim0 := &Epoch{
Index: 3,
FirstBlock: 3,
LastBlock: 3,
Expand All @@ -230,14 +220,14 @@ func (s *EvmReaderSuite) TestReadClaimAcceptance() {
s.repository.On("GetEpoch",
mock.Anything,
mock.Anything,
mock.Anything).Return(claim1, nil)
mock.Anything).Return(claim0, nil)

s.repository.Unset("GetEpochsWithOpenClaims")
s.repository.On("GetEpochsWithOpenClaims",
mock.Anything,
mock.Anything,
mock.Anything,
).Return([]*Epoch{claim0}, nil)
).Return([]*Epoch{}, nil)

s.repository.Unset("UpdateEpochs")
s.repository.On("UpdateEpochs",
Expand All @@ -248,14 +238,10 @@ func (s *EvmReaderSuite) TestReadClaimAcceptance() {
obj := arguments.Get(1)
claims, ok := obj.([]*Epoch)
s.Require().True(ok)
s.Require().Equal(2, len(claims))
s.Require().Equal(1, len(claims))
claim0 := claims[0]
claim1 := claims[1]
s.Require().NotNil(claim0)
s.Require().Equal(uint64(1), claim0.LastBlock)
s.Require().Equal(EpochStatusClaimRejected, claim0.Status)
s.Require().Equal(uint64(3), claim1.LastBlock)
s.Require().Equal(EpochStatusClaimAccepted, claim1.Status)
s.Require().Equal(uint64(3), claim0.LastBlock)
s.Require().Equal(EpochStatusClaimAccepted, claim0.Status)

}).Return(nil)

Expand Down Expand Up @@ -291,7 +277,7 @@ func (s *EvmReaderSuite) TestReadClaimAcceptance() {
}

wsClient.fireNewHead(&header0)
time.Sleep(1 * time.Second)
time.Sleep(10 * time.Second)

s.repository.AssertNumberOfCalls(
s.T(),
Expand Down Expand Up @@ -589,4 +575,142 @@ func (s *EvmReaderSuite) TestCheckClaimFails() {
)

})

s.Run("whenHasPreviousOpenClaims", func() {

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

appAddress := common.HexToAddress("0x2E663fe9aE92275242406A185AA4fC8174339D3E")

// Contract Factory

consensusContract := &MockIConsensusContract{}

contractFactory := newEmvReaderContractFactory()

contractFactory.Unset("NewIConsensus")
contractFactory.On("NewIConsensus",
mock.Anything,
).Return(consensusContract, nil)

//New EVM Reader
wsClient := FakeWSEhtClient{}
evmReader := NewEvmReader(
s.client,
&wsClient,
s.inputBox,
s.repository,
0x00,
DefaultBlockStatusLatest,
contractFactory,
)

// Prepare Claims Acceptance Events

claimEvent0 := &iconsensus.IConsensusClaimAcceptance{
AppContract: appAddress,
LastProcessedBlockNumber: big.NewInt(3),
Claim: common.HexToHash("0xdeadbeef"),
}

claimEvents := []*iconsensus.IConsensusClaimAcceptance{claimEvent0}
consensusContract.On("RetrieveClaimAcceptanceEvents",
mock.Anything,
mock.Anything,
).Return(claimEvents, nil).Once()
consensusContract.On("RetrieveClaimAcceptanceEvents",
mock.Anything,
mock.Anything,
).Return([]*iconsensus.IConsensusClaimAcceptance{}, nil)

// Epoch Length
consensusContract.On("GetEpochLength",
mock.Anything,
).Return(big.NewInt(1), nil).Once()

// Prepare repository
s.repository.Unset("GetAllRunningApplications")
s.repository.On(
"GetAllRunningApplications",
mock.Anything,
).Return([]Application{{
ContractAddress: appAddress,
IConsensusAddress: common.HexToAddress("0xdeadbeef"),
LastClaimCheckBlock: 0x10,
}}, nil).Once()
s.repository.On(
"GetAllRunningApplications",
mock.Anything,
).Return([]Application{{
ContractAddress: appAddress,
IConsensusAddress: common.HexToAddress("0xdeadbeef"),
LastClaimCheckBlock: 0x11,
}}, nil).Once()

claim0Hash := common.HexToHash("0xdeadbeef")
claim0 := &Epoch{
Index: 1,
FirstBlock: 1,
LastBlock: 1,
AppAddress: appAddress,
Status: EpochStatusClaimSubmitted,
ClaimHash: &claim0Hash,
}

s.repository.Unset("GetEpochsWithOpenClaims")
s.repository.On("GetEpochsWithOpenClaims",
mock.Anything,
mock.Anything,
mock.Anything,
).Return([]*Epoch{claim0}, nil)

s.repository.Unset("UpdateEpochs")
s.repository.On("UpdateEpochs",
mock.Anything,
mock.Anything,
mock.Anything,
).Return(nil)

//No Inputs
s.inputBox.Unset("RetrieveInputs")
s.inputBox.On("RetrieveInputs",
mock.Anything,
mock.Anything,
mock.Anything,
).Return([]inputbox.InputBoxInputAdded{}, nil)

// Prepare Client
s.client.Unset("HeaderByNumber")
s.client.On(
"HeaderByNumber",
mock.Anything,
mock.Anything,
).Return(&header0, nil).Once()

// Start service
ready := make(chan struct{}, 1)
errChannel := make(chan error, 1)

go func() {
errChannel <- evmReader.Run(ctx, ready)
}()

select {
case <-ready:
break
case err := <-errChannel:
s.FailNow("unexpected error signal", err)
}

wsClient.fireNewHead(&header0)
time.Sleep(1 * time.Second)

s.repository.AssertNumberOfCalls(
s.T(),
"UpdateEpochs",
0,
)

})
}
1 change: 1 addition & 0 deletions internal/evmreader/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ func calculateEpochIndex(epochLength uint64, blockNumber uint64) uint64 {
return blockNumber / epochLength
}

// appsToAddresses
func appsToAddresses(apps []application) []Address {
var addresses []Address
for _, app := range apps {
Expand Down
16 changes: 9 additions & 7 deletions internal/repository/evmreader.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ import (
)

var (
errInsertInputs = errors.New("unable to insert inputs")
errUpdateEpochs = errors.New("unable to update epochs status")
errInsertInputs = errors.New("unable to insert inputs")
errUpdateEpochs = errors.New("unable to update epochs status")
errGetEpochWithOpenClaims = errors.New("failed to get epochs with open claims")
errGetAllApplications = errors.New("failed to get Applications")
)

// This method should be called at the end of EVMReader read input cycle
Expand Down Expand Up @@ -186,13 +188,13 @@ func (pg *Database) getAllApplicationsByStatus(

var args []any
if criteria != nil {
query = query + "WHERE status=$1"
query = query + " WHERE status=$1"
args = append(args, string(*criteria))
}

rows, err := pg.db.Query(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("Query failed: %v\n", err)
return nil, errors.Join(errGetAllApplications, err)
}

_, err = pgx.ForEachRow(rows,
Expand All @@ -212,7 +214,7 @@ func (pg *Database) getAllApplicationsByStatus(
return nil
})
if err != nil {
return nil, fmt.Errorf("ForEachRow failed: %w\n", err)
return nil, errors.Join(errGetAllApplications, err)
}

return results, nil
Expand Down Expand Up @@ -276,7 +278,7 @@ func (pg *Database) GetEpochsWithOpenClaims(

rows, err := pg.db.Query(ctx, query, args)
if err != nil {
return nil, fmt.Errorf("GetEpochsWithOpenClaims failed: %w", err)
return nil, errors.Join(errGetEpochWithOpenClaims, err)
}

var (
Expand Down Expand Up @@ -305,7 +307,7 @@ func (pg *Database) GetEpochsWithOpenClaims(
return nil
})
if err != nil {
return nil, fmt.Errorf("GetEpochsWithOpenClaims failed: %w", err)
return nil, errors.Join(errGetEpochWithOpenClaims, err)
}
return results, nil
}
Expand Down

0 comments on commit 0e09f60

Please sign in to comment.