Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Access] Use Indexed height when checking payer balance #6292

Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
35d4f42
Extended ProtocolStateBlocks to return indexed height, updated height…
AndriiDiachuk Aug 1, 2024
d795264
Fixed check for threshold between heights
AndriiDiachuk Aug 1, 2024
bba3a12
Changed check of gap, added test for error case
AndriiDiachuk Aug 7, 2024
8c1b515
Added replace statement for flow-emulator
AndriiDiachuk Aug 7, 2024
f648a5c
Merged
AndriiDiachuk Aug 7, 2024
28c030c
Merged
AndriiDiachuk Aug 7, 2024
47e957e
Fixed remarks
AndriiDiachuk Aug 15, 2024
ffd6bcc
Merged
AndriiDiachuk Aug 15, 2024
3ebbc5e
Updated replace
AndriiDiachuk Aug 15, 2024
36b2c55
Added godoc and expected errors
AndriiDiachuk Aug 19, 2024
0d05d2f
Added indexReporter to observer builder
AndriiDiachuk Aug 19, 2024
f02dd0d
Merge branch 'master' into use-indexed-height-checking-payer-balance
AndriiDiachuk Aug 19, 2024
f6bcd8d
Merge branch 'master' into use-indexed-height-checking-payer-balance
AndriiDiachuk Aug 20, 2024
4e46606
Update validator.go
AndriiDiachuk Aug 26, 2024
ae63dd6
Merged
AndriiDiachuk Aug 27, 2024
0ed15f2
Updated replace
AndriiDiachuk Aug 27, 2024
311fa8f
Merged
AndriiDiachuk Aug 29, 2024
f841c29
Added gosec statement
AndriiDiachuk Aug 29, 2024
2d1c131
Merged conflicts
AndriiDiachuk Aug 30, 2024
a4a4cef
Merge branch 'master' of github.com:AndriiDiachuk/flow-go into use-in…
AndriiDiachuk Sep 3, 2024
160b0e0
Updated flow-emulator replace statement
AndriiDiachuk Sep 3, 2024
af7264b
Merge branch 'master' of github.com:AndriiDiachuk/flow-go into use-in…
AndriiDiachuk Sep 5, 2024
47f745c
Merge branch 'master' of github.com:AndriiDiachuk/flow-go into use-in…
AndriiDiachuk Sep 12, 2024
a57bf22
Merge branch 'master' of github.com:AndriiDiachuk/flow-go into use-in…
AndriiDiachuk Sep 12, 2024
adede15
Merge branch 'master' of github.com:AndriiDiachuk/flow-go into use-in…
AndriiDiachuk Sep 26, 2024
bfa3662
Merge branch 'master' into use-indexed-height-checking-payer-balance
AndriiDiachuk Sep 27, 2024
738e3ba
Merged
AndriiDiachuk Sep 30, 2024
0268599
Merge branch 'use-indexed-height-checking-payer-balance' of github.co…
AndriiDiachuk Sep 30, 2024
31ef3d3
Updated flow-emulator dependencies
AndriiDiachuk Sep 30, 2024
f1a4687
Linted
AndriiDiachuk Sep 30, 2024
7015c6a
Merged with master
AndriiDiachuk Oct 2, 2024
0a7f162
Updated flow-emulator commit
AndriiDiachuk Oct 2, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions access/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import (
// ErrUnknownReferenceBlock indicates that a transaction references an unknown block.
var ErrUnknownReferenceBlock = errors.New("unknown reference block")

// IndexReporterNotInitialized is returned when indexReporter is nil because
// execution data syncing and indexing is disabled
var IndexReporterNotInitialized = errors.New("index reported not initialized")

// IncompleteTransactionError indicates that a transaction is missing one or more required fields.
type IncompleteTransactionError struct {
MissingFields []string
Expand Down Expand Up @@ -115,3 +119,14 @@ func IsInsufficientBalanceError(err error) bool {
var balanceError InsufficientBalanceError
return errors.As(err, &balanceError)
}

// IndexedHeightFarBehindError indicates that a node is far behind on indexing.
type IndexedHeightFarBehindError struct {
SealedHeight uint64
IndexedHeight uint64
}

func (e IndexedHeightFarBehindError) Error() string {
return fmt.Sprintf("the difference between the latest sealed height (%d) and indexed height (%d) exceeds the maximum gap allowed",
e.SealedHeight, e.IndexedHeight)
}
28 changes: 28 additions & 0 deletions access/mock/blocks.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 34 additions & 5 deletions access/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,32 @@ import (
"github.com/onflow/flow-go/fvm/systemcontracts"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/module/execution"
"github.com/onflow/flow-go/module/state_synchronization"
"github.com/onflow/flow-go/state"
"github.com/onflow/flow-go/state/protocol"
)

// DefaultSealedIndexedHeightThreshold is the default number of blocks between sealed and indexed height
// this sets a limit on how far into the past the payer validator will allow for checking the payer's balance.
const DefaultSealedIndexedHeightThreshold = 30

type Blocks interface {
HeaderByID(id flow.Identifier) (*flow.Header, error)
FinalizedHeader() (*flow.Header, error)
SealedHeader() (*flow.Header, error)
IndexedHeight() (uint64, error)
}

type ProtocolStateBlocks struct {
state protocol.State
state protocol.State
indexReporter state_synchronization.IndexReporter
}

func NewProtocolStateBlocks(state protocol.State) *ProtocolStateBlocks {
return &ProtocolStateBlocks{state: state}
func NewProtocolStateBlocks(state protocol.State, indexReporter state_synchronization.IndexReporter) *ProtocolStateBlocks {
return &ProtocolStateBlocks{
state: state,
indexReporter: indexReporter,
}
}

func (b *ProtocolStateBlocks) HeaderByID(id flow.Identifier) (*flow.Header, error) {
Expand All @@ -53,7 +63,16 @@ func (b *ProtocolStateBlocks) FinalizedHeader() (*flow.Header, error) {
}

func (b *ProtocolStateBlocks) SealedHeader() (*flow.Header, error) {

return b.state.Sealed().Head()

}

func (b *ProtocolStateBlocks) IndexedHeight() (uint64, error) {
AndriiDiachuk marked this conversation as resolved.
Show resolved Hide resolved
if b.indexReporter != nil {
return b.indexReporter.HighestIndexedHeight()
}
return 0, IndexReporterNotInitialized
}

// RateLimiter is an interface for checking if an address is rate limited.
Expand Down Expand Up @@ -396,6 +415,16 @@ func (v *TransactionValidator) checkSufficientBalanceToPayForTransaction(ctx con
return fmt.Errorf("could not fetch block header: %w", err)
}

indexedHeight, err := v.blocks.IndexedHeight()
if err != nil {
return fmt.Errorf("could not get indexed height: %w", err)
}

sealedHeight := header.Height
AndriiDiachuk marked this conversation as resolved.
Show resolved Hide resolved
if indexedHeight < sealedHeight-DefaultSealedIndexedHeightThreshold {
return IndexedHeightFarBehindError{SealedHeight: sealedHeight, IndexedHeight: indexedHeight}
}

payerAddress := cadence.NewAddress(tx.Payer)
inclusionEffort := cadence.UFix64(tx.InclusionEffort())
gasLimit := cadence.UFix64(tx.GasLimit)
Expand All @@ -405,7 +434,7 @@ func (v *TransactionValidator) checkSufficientBalanceToPayForTransaction(ctx con
return fmt.Errorf("failed to encode cadence args for script executor: %w", err)
}

result, err := v.scriptExecutor.ExecuteAtBlockHeight(ctx, v.verifyPayerBalanceScript, args, header.Height)
result, err := v.scriptExecutor.ExecuteAtBlockHeight(ctx, v.verifyPayerBalanceScript, args, indexedHeight)
if err != nil {
return fmt.Errorf("script finished with error: %w", err)
}
Expand All @@ -421,7 +450,7 @@ func (v *TransactionValidator) checkSufficientBalanceToPayForTransaction(ctx con
}

// return no error if payer has sufficient balance
if bool(canExecuteTransaction) {
if canExecuteTransaction {
AndriiDiachuk marked this conversation as resolved.
Show resolved Hide resolved
return nil
}

Expand Down
33 changes: 33 additions & 0 deletions access/validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ func (s *TransactionValidatorSuite) TestTransactionValidator_ScriptExecutorInter
scriptExecutor := execmock.NewScriptExecutor(s.T())
assert.NotNil(s.T(), scriptExecutor)

s.blocks.
On("IndexedHeight").
Return(s.header.Height, nil)

scriptExecutor.
On("ExecuteAtBlockHeight", mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(nil, errors.New("script executor internal error")).
Expand Down Expand Up @@ -111,6 +115,10 @@ func (s *TransactionValidatorSuite) TestTransactionValidator_SufficientBalance()
actualResponse, err := jsoncdc.Encode(actualResponseValue)
assert.NoError(s.T(), err)

s.blocks.
On("IndexedHeight").
Return(s.header.Height, nil)

scriptExecutor.
On("ExecuteAtBlockHeight", mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(actualResponse, nil).
Expand Down Expand Up @@ -138,6 +146,10 @@ func (s *TransactionValidatorSuite) TestTransactionValidator_InsufficientBalance
actualResponse, err := jsoncdc.Encode(actualResponseValue)
assert.NoError(s.T(), err)

s.blocks.
On("IndexedHeight").
Return(s.header.Height, nil)

scriptExecutor.
On("ExecuteAtBlockHeight", mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(actualResponse, nil).
Expand All @@ -162,3 +174,24 @@ func (s *TransactionValidatorSuite) TestTransactionValidator_InsufficientBalance

assert.ErrorIs(s.T(), actualErr, expectedError)
}

func (s *TransactionValidatorSuite) TestTransactionValidator_SealedIndexedHeightThresholdLimit() {
scriptExecutor := execmock.NewScriptExecutor(s.T())

// setting indexed height to be behind of sealed by bigger number than allowed(DefaultSealedIndexedHeightThreshold)
indexedHeight := s.header.Height - 40

s.blocks.
On("IndexedHeight").
Return(indexedHeight, nil)

validator, err := access.NewTransactionValidator(s.blocks, s.chain, s.validatorOptions, scriptExecutor)
assert.NoError(s.T(), err)
assert.NotNil(s.T(), validator)

txBody := unittest.TransactionBodyFixture()

err = validator.Validate(context.Background(), &txBody)
assert.NoError(s.T(), err)

}
13 changes: 7 additions & 6 deletions cmd/access/node_builder/access_node_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -1883,6 +1883,12 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) {
return nil, fmt.Errorf("transaction result query mode 'compare' is not supported")
}

// If execution data syncing and indexing is disabled, pass nil indexReporter
var indexReporter state_synchronization.IndexReporter
if builder.executionDataSyncEnabled && builder.executionDataIndexingEnabled {
indexReporter = builder.Reporter
}

nodeBackend, err := backend.New(backend.Params{
State: node.State,
CollectionRPC: builder.CollectionRPC,
Expand Down Expand Up @@ -1921,17 +1927,12 @@ func (builder *FlowAccessNodeBuilder) Build() (cmd.Node, error) {
TxResultQueryMode: txResultQueryMode,
TxResultsIndex: builder.TxResultsIndex,
LastFullBlockHeight: lastFullBlockHeight,
IndexReporter: indexReporter,
AndriiDiachuk marked this conversation as resolved.
Show resolved Hide resolved
})
if err != nil {
return nil, fmt.Errorf("could not initialize backend: %w", err)
}

// If execution data syncing and indexing is disabled, pass nil indexReporter
var indexReporter state_synchronization.IndexReporter
if builder.executionDataSyncEnabled && builder.executionDataIndexingEnabled {
indexReporter = builder.Reporter
}

engineBuilder, err := rpc.NewBuilder(
node.Logger,
node.State,
Expand Down
20 changes: 17 additions & 3 deletions engine/access/rpc/backend/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/module/counters"
"github.com/onflow/flow-go/module/execution"
"github.com/onflow/flow-go/module/state_synchronization"
"github.com/onflow/flow-go/state/protocol"
"github.com/onflow/flow-go/storage"
)
Expand Down Expand Up @@ -119,6 +120,7 @@ type Params struct {
TxResultQueryMode IndexQueryMode
TxResultsIndex *index.TransactionResultsIndex
LastFullBlockHeight *counters.PersistentStrictMonotonicCounter
IndexReporter state_synchronization.IndexReporter
}

var _ TransactionErrorMessage = (*Backend)(nil)
Expand Down Expand Up @@ -246,7 +248,13 @@ func New(params Params) (*Backend, error) {
nodeInfo: nodeInfo,
}

txValidator, err := configureTransactionValidator(params.State, params.ChainID, params.ScriptExecutor, params.CheckPayerBalance)
txValidator, err := configureTransactionValidator(
params.State,
params.ChainID,
params.ScriptExecutor,
params.IndexReporter,
params.CheckPayerBalance,
)
if err != nil {
return nil, fmt.Errorf("could not create transaction validator: %w", err)
}
Expand Down Expand Up @@ -310,9 +318,15 @@ func identifierList(ids []string) (flow.IdentifierList, error) {
return idList, nil
}

func configureTransactionValidator(state protocol.State, chainID flow.ChainID, executor execution.ScriptExecutor, checkPayerBalance bool) (*access.TransactionValidator, error) {
func configureTransactionValidator(
state protocol.State,
chainID flow.ChainID,
executor execution.ScriptExecutor,
indexReporter state_synchronization.IndexReporter,
checkPayerBalance bool,
) (*access.TransactionValidator, error) {
return access.NewTransactionValidator(
access.NewProtocolStateBlocks(state),
access.NewProtocolStateBlocks(state, indexReporter),
chainID.Chain(),
access.TransactionValidationOptions{
Expiry: flow.DefaultTransactionExpiry,
Expand Down
3 changes: 1 addition & 2 deletions engine/access/rpc/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import (
"net/http"
"sync"

"github.com/onflow/flow-go/module/state_synchronization"

"github.com/rs/zerolog"
"google.golang.org/grpc/credentials"

Expand All @@ -25,6 +23,7 @@ import (
"github.com/onflow/flow-go/module/events"
"github.com/onflow/flow-go/module/grpcserver"
"github.com/onflow/flow-go/module/irrecoverable"
"github.com/onflow/flow-go/module/state_synchronization"
"github.com/onflow/flow-go/state/protocol"
)

Expand Down
2 changes: 1 addition & 1 deletion engine/collection/ingest/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func New(
logger := log.With().Str("engine", "ingest").Logger()

transactionValidator := access.NewTransactionValidatorWithLimiter(
access.NewProtocolStateBlocks(state),
access.NewProtocolStateBlocks(state, nil),
chain,
access.TransactionValidationOptions{
Expiry: flow.DefaultTransactionExpiry,
Expand Down
5 changes: 4 additions & 1 deletion integration/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ require (
github.com/onflow/flow-core-contracts/lib/go/contracts v1.3.1
github.com/onflow/flow-core-contracts/lib/go/templates v1.3.1
github.com/onflow/flow-emulator v1.0.0-preview.36.0.20240729195722-d4eb1c30eb9f
github.com/onflow/flow-go v0.36.8-0.20240729193633-433a32eeb0cd
github.com/onflow/flow-go v0.37.1
github.com/onflow/flow-go-sdk v1.0.0-preview.50
github.com/onflow/flow-go/insecure v0.0.0-00010101000000-000000000000
github.com/onflow/flow/protobuf/go/flow v0.4.5
Expand Down Expand Up @@ -360,5 +360,8 @@ replace github.com/onflow/flow-go => ../

replace github.com/onflow/flow-go/insecure => ../insecure

// TODO: remove it when https://github.com/onflow/flow-emulator/pull/724 merged
replace github.com/onflow/flow-emulator v1.0.0-preview.36.0.20240729195722-d4eb1c30eb9f => github.com/AndriiDiachuk/flow-emulator v0.0.0-20240815104502-fab42f5691e1

// TODO: remove it when https://github.com/ipfs/go-ds-pebble/pull/36 merged
replace github.com/ipfs/go-ds-pebble v0.3.1 => github.com/onflow/go-ds-pebble v0.0.0-20240731130313-f186539f382c
4 changes: 2 additions & 2 deletions integration/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -949,6 +949,8 @@ gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zum
git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg=
git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3pc=
github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8=
github.com/AndriiDiachuk/flow-emulator v0.0.0-20240815104502-fab42f5691e1 h1:G/CkcyLNr1bL+CAWTktojKOXWtSRW8tJ04QIrvN1+68=
github.com/AndriiDiachuk/flow-emulator v0.0.0-20240815104502-fab42f5691e1/go.mod h1:xaDAJhLjqQMPl6g0J691mp6crgdvKGFqo0KDeJRYY9E=
github.com/Azure/azure-sdk-for-go/sdk/azcore v0.21.1/go.mod h1:fBF9PQNqB8scdgpZ3ufzaLntG0AG7C1WjPMsiFOmfHM=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.0.0/go.mod h1:uGG2W01BaETf0Ozp+QxxKJdMBNRWPdstHG0Fmdwn1/U=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.6.0/go.mod h1:bjGvMhVMb+EEm3VRNQawDMUyMMjo+S5ewNjflkep/0Q=
Expand Down Expand Up @@ -2151,8 +2153,6 @@ github.com/onflow/flow-core-contracts/lib/go/contracts v1.3.1 h1:q9tXLIALwQ76bO4
github.com/onflow/flow-core-contracts/lib/go/contracts v1.3.1/go.mod h1:u/mkP/B+PbV33tEG3qfkhhBlydSvAKxfLZSfB4lsJHg=
github.com/onflow/flow-core-contracts/lib/go/templates v1.3.1 h1:FfhMBAb78p6VAWkJ+iqdKLErGQVQgxk5w6DP5ZruWX8=
github.com/onflow/flow-core-contracts/lib/go/templates v1.3.1/go.mod h1:NgbMOYnMh0GN48VsNKZuiwK7uyk38Wyo8jN9+C9QE30=
github.com/onflow/flow-emulator v1.0.0-preview.36.0.20240729195722-d4eb1c30eb9f h1:2Ejpmm2Vrl/XLaE6lniE1vNfi6WYhzqHiCk6oomGoFE=
github.com/onflow/flow-emulator v1.0.0-preview.36.0.20240729195722-d4eb1c30eb9f/go.mod h1:0rqp896zEcjNqqDiQNBUlpS/7nzS4+E+yG/4s0P13bQ=
github.com/onflow/flow-ft/lib/go/contracts v1.0.0 h1:mToacZ5NWqtlWwk/7RgIl/jeKB/Sy/tIXdw90yKHcV0=
github.com/onflow/flow-ft/lib/go/contracts v1.0.0/go.mod h1:PwsL8fC81cjnUnTfmyL/HOIyHnyaw/JA474Wfj2tl6A=
github.com/onflow/flow-ft/lib/go/templates v1.0.0 h1:6cMS/lUJJ17HjKBfMO/eh0GGvnpElPgBXx7h5aoWJhs=
Expand Down
Loading