graphql: fixes missing tx logs (#25745)

* graphql: fix tx logs

* graphql: refactor test service setup

* graphql: add test for tx logs
pull/25767/head
Sina Mahmoodi 2 years ago committed by GitHub
parent 9a3bd114e7
commit 818ff32ff5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      graphql/graphql.go
  2. 225
      graphql/graphql_test.go
  3. 9
      graphql/service.go

@ -481,7 +481,7 @@ func (t *Transaction) getLogs(ctx context.Context) (*[]*Log, error) {
}
var ret []*Log
// Select tx logs from all block logs
ix := sort.Search(len(logs), func(i int) bool { return uint64(logs[i].TxIndex) == t.index })
ix := sort.Search(len(logs), func(i int) bool { return uint64(logs[i].TxIndex) >= t.index })
for ix < len(logs) && uint64(logs[ix].TxIndex) == t.index {
ret = append(ret, &Log{
r: t.r,

@ -17,6 +17,8 @@
package graphql
import (
"context"
"encoding/json"
"fmt"
"io"
"math/big"
@ -51,15 +53,21 @@ func TestBuildSchema(t *testing.T) {
}
defer stack.Close()
// Make sure the schema can be parsed and matched up to the object model.
if err := newHandler(stack, nil, nil, []string{}, []string{}); err != nil {
if _, err := newHandler(stack, nil, nil, []string{}, []string{}); err != nil {
t.Errorf("Could not construct GraphQL handler: %v", err)
}
}
// Tests that a graphQL request is successfully handled when graphql is enabled on the specified endpoint
func TestGraphQLBlockSerialization(t *testing.T) {
stack := createNode(t, true, false)
stack := createNode(t)
defer stack.Close()
genesis := &core.Genesis{
Config: params.AllEthashProtocolChanges,
GasLimit: 11500000,
Difficulty: big.NewInt(1048576),
}
newGQLService(t, stack, genesis, 10, func(i int, gen *core.BlockGen) {})
// start node
if err := stack.Start(); err != nil {
t.Fatalf("could not start node: %v", err)
@ -161,8 +169,55 @@ func TestGraphQLBlockSerialization(t *testing.T) {
}
func TestGraphQLBlockSerializationEIP2718(t *testing.T) {
stack := createNode(t, true, true)
// Account for signing txes
var (
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
address = crypto.PubkeyToAddress(key.PublicKey)
funds = big.NewInt(1000000000000000)
dad = common.HexToAddress("0x0000000000000000000000000000000000000dad")
)
stack := createNode(t)
defer stack.Close()
genesis := &core.Genesis{
Config: params.AllEthashProtocolChanges,
GasLimit: 11500000,
Difficulty: big.NewInt(1048576),
Alloc: core.GenesisAlloc{
address: {Balance: funds},
// The address 0xdad sloads 0x00 and 0x01
dad: {
Code: []byte{byte(vm.PC), byte(vm.PC), byte(vm.SLOAD), byte(vm.SLOAD)},
Nonce: 0,
Balance: big.NewInt(0),
},
},
BaseFee: big.NewInt(params.InitialBaseFee),
}
signer := types.LatestSigner(genesis.Config)
newGQLService(t, stack, genesis, 1, func(i int, gen *core.BlockGen) {
gen.SetCoinbase(common.Address{1})
tx, _ := types.SignNewTx(key, signer, &types.LegacyTx{
Nonce: uint64(0),
To: &dad,
Value: big.NewInt(100),
Gas: 50000,
GasPrice: big.NewInt(params.InitialBaseFee),
})
gen.AddTx(tx)
tx, _ = types.SignNewTx(key, signer, &types.AccessListTx{
ChainID: genesis.Config.ChainID,
Nonce: uint64(1),
To: &dad,
Gas: 30000,
GasPrice: big.NewInt(params.InitialBaseFee),
Value: big.NewInt(50),
AccessList: types.AccessList{{
Address: dad,
StorageKeys: []common.Hash{{0}},
}},
})
gen.AddTx(tx)
})
// start node
if err := stack.Start(); err != nil {
t.Fatalf("could not start node: %v", err)
@ -198,7 +253,7 @@ func TestGraphQLBlockSerializationEIP2718(t *testing.T) {
// Tests that a graphQL request is not handled successfully when graphql is not enabled on the specified endpoint
func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
stack := createNode(t, false, false)
stack := createNode(t)
defer stack.Close()
if err := stack.Start(); err != nil {
t.Fatalf("could not start node: %v", err)
@ -212,93 +267,74 @@ func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
}
func createNode(t *testing.T, gqlEnabled bool, txEnabled bool) *node.Node {
stack, err := node.New(&node.Config{
HTTPHost: "127.0.0.1",
HTTPPort: 0,
WSHost: "127.0.0.1",
WSPort: 0,
})
if err != nil {
t.Fatalf("could not create node: %v", err)
}
if !gqlEnabled {
return stack
}
if !txEnabled {
createGQLService(t, stack)
} else {
createGQLServiceWithTransactions(t, stack)
}
return stack
}
func createGQLService(t *testing.T, stack *node.Node) {
// create backend
ethConf := &ethconfig.Config{
Genesis: &core.Genesis{
func TestGraphQLTransactionLogs(t *testing.T) {
var (
key, _ = crypto.GenerateKey()
addr = crypto.PubkeyToAddress(key.PublicKey)
dadStr = "0x0000000000000000000000000000000000000dad"
dad = common.HexToAddress(dadStr)
genesis = &core.Genesis{
Config: params.AllEthashProtocolChanges,
GasLimit: 11500000,
Difficulty: big.NewInt(1048576),
Alloc: core.GenesisAlloc{
addr: {Balance: big.NewInt(params.Ether)},
dad: {
// LOG0(0, 0), LOG0(0, 0), RETURN(0, 0)
Code: common.Hex2Bytes("60006000a060006000a060006000f3"),
Nonce: 0,
Balance: big.NewInt(0),
},
Ethash: ethash.Config{
PowMode: ethash.ModeFake,
},
NetworkId: 1337,
TrieCleanCache: 5,
TrieCleanCacheJournal: "triecache",
TrieCleanCacheRejournal: 60 * time.Minute,
TrieDirtyCache: 5,
TrieTimeout: 60 * time.Minute,
SnapshotCache: 5,
}
ethBackend, err := eth.New(stack, ethConf)
if err != nil {
t.Fatalf("could not create eth backend: %v", err)
signer = types.LatestSigner(genesis.Config)
stack = createNode(t)
)
defer stack.Close()
handler := newGQLService(t, stack, genesis, 1, func(i int, gen *core.BlockGen) {
tx, _ := types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)})
gen.AddTx(tx)
tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 1, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)})
gen.AddTx(tx)
tx, _ = types.SignNewTx(key, signer, &types.LegacyTx{To: &dad, Nonce: 2, Gas: 100000, GasPrice: big.NewInt(params.InitialBaseFee)})
gen.AddTx(tx)
})
// start node
if err := stack.Start(); err != nil {
t.Fatalf("could not start node: %v", err)
}
// Create some blocks and import them
chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(),
ethash.NewFaker(), ethBackend.ChainDb(), 10, func(i int, gen *core.BlockGen) {})
_, err = ethBackend.BlockChain().InsertChain(chain)
if err != nil {
t.Fatalf("could not create import blocks: %v", err)
query := `{block { transactions { logs { account { address } } } } }`
res := handler.Schema.Exec(context.Background(), query, "", map[string]interface{}{})
if res.Errors != nil {
t.Fatalf("graphql query failed: %v", res.Errors)
}
// create gql service
filterSystem := filters.NewFilterSystem(ethBackend.APIBackend, filters.Config{})
err = New(stack, ethBackend.APIBackend, filterSystem, []string{}, []string{})
have, err := json.Marshal(res.Data)
if err != nil {
t.Fatalf("could not create graphql service: %v", err)
t.Fatalf("failed to encode graphql response: %s", err)
}
want := fmt.Sprintf(`{"block":{"transactions":[{"logs":[{"account":{"address":"%s"}},{"account":{"address":"%s"}}]},{"logs":[{"account":{"address":"%s"}},{"account":{"address":"%s"}}]},{"logs":[{"account":{"address":"%s"}},{"account":{"address":"%s"}}]}]}}`, dadStr, dadStr, dadStr, dadStr, dadStr, dadStr)
if string(have) != want {
t.Errorf("response unmatch. expected %s, got %s", want, have)
}
}
func createGQLServiceWithTransactions(t *testing.T, stack *node.Node) {
// create backend
key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
address := crypto.PubkeyToAddress(key.PublicKey)
funds := big.NewInt(1000000000000000)
dad := common.HexToAddress("0x0000000000000000000000000000000000000dad")
func createNode(t *testing.T) *node.Node {
stack, err := node.New(&node.Config{
HTTPHost: "127.0.0.1",
HTTPPort: 0,
WSHost: "127.0.0.1",
WSPort: 0,
})
if err != nil {
t.Fatalf("could not create node: %v", err)
}
return stack
}
func newGQLService(t *testing.T, stack *node.Node, gspec *core.Genesis, genBlocks int, genfunc func(i int, gen *core.BlockGen)) *handler {
ethConf := &ethconfig.Config{
Genesis: &core.Genesis{
Config: params.AllEthashProtocolChanges,
GasLimit: 11500000,
Difficulty: big.NewInt(1048576),
Alloc: core.GenesisAlloc{
address: {Balance: funds},
// The address 0xdad sloads 0x00 and 0x01
dad: {
Code: []byte{
byte(vm.PC),
byte(vm.PC),
byte(vm.SLOAD),
byte(vm.SLOAD),
},
Nonce: 0,
Balance: big.NewInt(0),
},
},
BaseFee: big.NewInt(params.InitialBaseFee),
},
Genesis: gspec,
Ethash: ethash.Config{
PowMode: ethash.ModeFake,
},
@ -310,49 +346,22 @@ func createGQLServiceWithTransactions(t *testing.T, stack *node.Node) {
TrieTimeout: 60 * time.Minute,
SnapshotCache: 5,
}
ethBackend, err := eth.New(stack, ethConf)
if err != nil {
t.Fatalf("could not create eth backend: %v", err)
}
signer := types.LatestSigner(ethConf.Genesis.Config)
legacyTx, _ := types.SignNewTx(key, signer, &types.LegacyTx{
Nonce: uint64(0),
To: &dad,
Value: big.NewInt(100),
Gas: 50000,
GasPrice: big.NewInt(params.InitialBaseFee),
})
envelopTx, _ := types.SignNewTx(key, signer, &types.AccessListTx{
ChainID: ethConf.Genesis.Config.ChainID,
Nonce: uint64(1),
To: &dad,
Gas: 30000,
GasPrice: big.NewInt(params.InitialBaseFee),
Value: big.NewInt(50),
AccessList: types.AccessList{{
Address: dad,
StorageKeys: []common.Hash{{0}},
}},
})
// Create some blocks and import them
chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(),
ethash.NewFaker(), ethBackend.ChainDb(), 1, func(i int, b *core.BlockGen) {
b.SetCoinbase(common.Address{1})
b.AddTx(legacyTx)
b.AddTx(envelopTx)
})
ethash.NewFaker(), ethBackend.ChainDb(), genBlocks, genfunc)
_, err = ethBackend.BlockChain().InsertChain(chain)
if err != nil {
t.Fatalf("could not create import blocks: %v", err)
}
// create gql service
// Set up handler
filterSystem := filters.NewFilterSystem(ethBackend.APIBackend, filters.Config{})
err = New(stack, ethBackend.APIBackend, filterSystem, []string{}, []string{})
handler, err := newHandler(stack, ethBackend.APIBackend, filterSystem, []string{}, []string{})
if err != nil {
t.Fatalf("could not create graphql service: %v", err)
}
return handler
}

@ -57,17 +57,18 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// New constructs a new GraphQL service instance.
func New(stack *node.Node, backend ethapi.Backend, filterSystem *filters.FilterSystem, cors, vhosts []string) error {
return newHandler(stack, backend, filterSystem, cors, vhosts)
_, err := newHandler(stack, backend, filterSystem, cors, vhosts)
return err
}
// newHandler returns a new `http.Handler` that will answer GraphQL queries.
// It additionally exports an interactive query browser on the / endpoint.
func newHandler(stack *node.Node, backend ethapi.Backend, filterSystem *filters.FilterSystem, cors, vhosts []string) error {
func newHandler(stack *node.Node, backend ethapi.Backend, filterSystem *filters.FilterSystem, cors, vhosts []string) (*handler, error) {
q := Resolver{backend, filterSystem}
s, err := graphql.ParseSchema(schema, &q)
if err != nil {
return err
return nil, err
}
h := handler{Schema: s}
handler := node.NewHTTPHandlerStack(h, cors, vhosts, nil)
@ -76,5 +77,5 @@ func newHandler(stack *node.Node, backend ethapi.Backend, filterSystem *filters.
stack.RegisterHandler("GraphQL", "/graphql", handler)
stack.RegisterHandler("GraphQL", "/graphql/", handler)
return nil
return &h, nil
}

Loading…
Cancel
Save