Skip to content

Commit

Permalink
Prevent panic in TransactionByHash for non-existent transactions
Browse files Browse the repository at this point in the history
When searching for a transaction in the pending block, the code would continue
to AdaptTransaction even if no matching transaction was found. This could lead
to a panic when trying to adapt a nil transaction. Added a nil check and an
early break from the loop to ensure we properly handle non-existent transactions
with ErrTxnHashNotFound.

Changes:
- Add break statement to exit loop once matching transaction is found
- Add explicit nil check for txn before attempting to adapt it
- Return ErrTxnHashNotFound if no matching transaction is found
  • Loading branch information
wojciechos committed Jan 14, 2025
1 parent d99e28b commit 3c1e532
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
5 changes: 5 additions & 0 deletions rpc/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -440,8 +440,13 @@ func (h *Handler) TransactionByHash(hash felt.Felt) (*Transaction, *jsonrpc.Erro
for _, t := range pendingB.Transactions {
if hash.Equal(t.Hash()) {
txn = t
break

Check warning on line 443 in rpc/transaction.go

View check run for this annotation

Codecov / codecov/patch

rpc/transaction.go#L443

Added line #L443 was not covered by tests
}
}

if txn == nil {
return nil, ErrTxnHashNotFound
}
}
return AdaptTransaction(txn), nil
}
Expand Down
26 changes: 26 additions & 0 deletions rpc/transaction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,32 @@ func TestTransactionByHashNotFound(t *testing.T) {
assert.Equal(t, rpc.ErrTxnHashNotFound, rpcErr)
}

func TestTransactionByHashNotFoundInPendingBlock(t *testing.T) {
mockCtrl := gomock.NewController(t)
t.Cleanup(mockCtrl.Finish)
mockReader := mocks.NewMockReader(mockCtrl)
mockSyncReader := mocks.NewMockSyncReader(mockCtrl)

searchTxHash := utils.HexToFelt(t, "0x123456")

otherTxHash := utils.HexToFelt(t, "0x789abc")
pendingTx := &core.InvokeTransaction{
TransactionHash: otherTxHash,
Version: new(core.TransactionVersion).SetUint64(1),
}

mockReader.EXPECT().TransactionByHash(searchTxHash).Return(nil, db.ErrKeyNotFound)
mockSyncReader.EXPECT().PendingBlock().Return(&core.Block{
Transactions: []core.Transaction{pendingTx},
})

handler := rpc.New(mockReader, mockSyncReader, nil, "", nil)

tx, rpcErr := handler.TransactionByHash(*searchTxHash)
assert.Nil(t, tx)
assert.Equal(t, rpc.ErrTxnHashNotFound, rpcErr)
}

func TestTransactionByHash(t *testing.T) {
tests := map[string]struct {
hash string
Expand Down

0 comments on commit 3c1e532

Please sign in to comment.