2015-12-16 10:58:01 +01:00
|
|
|
// Copyright 2015 The go-ethereum Authors
|
|
|
|
// This file is part of the go-ethereum library.
|
|
|
|
//
|
|
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU Lesser General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Lesser General Public License
|
|
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
package rpc
|
2015-10-15 16:07:19 +02:00
|
|
|
|
|
|
|
import (
|
2019-02-04 13:47:34 +01:00
|
|
|
"bufio"
|
|
|
|
"bytes"
|
|
|
|
"io"
|
2016-03-14 09:38:54 +01:00
|
|
|
"net"
|
2022-05-16 11:59:35 +02:00
|
|
|
"os"
|
2019-02-04 13:47:34 +01:00
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
2015-10-15 16:07:19 +02:00
|
|
|
"testing"
|
2016-07-12 17:47:15 +02:00
|
|
|
"time"
|
2015-10-15 16:07:19 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestServerRegisterName(t *testing.T) {
|
|
|
|
server := NewServer()
|
2019-02-04 13:47:34 +01:00
|
|
|
service := new(testService)
|
2015-10-15 16:07:19 +02:00
|
|
|
|
2019-02-04 13:47:34 +01:00
|
|
|
if err := server.RegisterName("test", service); err != nil {
|
2015-10-15 16:07:19 +02:00
|
|
|
t.Fatalf("%v", err)
|
|
|
|
}
|
|
|
|
|
2019-02-04 13:47:34 +01:00
|
|
|
if len(server.services.services) != 2 {
|
|
|
|
t.Fatalf("Expected 2 service entries, got %d", len(server.services.services))
|
2015-10-15 16:07:19 +02:00
|
|
|
}
|
|
|
|
|
2019-02-04 13:47:34 +01:00
|
|
|
svc, ok := server.services.services["test"]
|
2015-10-15 16:07:19 +02:00
|
|
|
if !ok {
|
|
|
|
t.Fatalf("Expected service calc to be registered")
|
|
|
|
}
|
|
|
|
|
2023-02-19 20:23:18 +01:00
|
|
|
wantCallbacks := 13
|
2019-02-04 13:47:34 +01:00
|
|
|
if len(svc.callbacks) != wantCallbacks {
|
|
|
|
t.Errorf("Expected %d callbacks for service 'service', got %d", wantCallbacks, len(svc.callbacks))
|
2015-10-15 16:07:19 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-04 13:47:34 +01:00
|
|
|
func TestServer(t *testing.T) {
|
2022-05-17 14:27:04 +02:00
|
|
|
files, err := os.ReadDir("testdata")
|
2019-02-04 13:47:34 +01:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal("where'd my testdata go?")
|
2015-10-15 16:07:19 +02:00
|
|
|
}
|
2019-02-04 13:47:34 +01:00
|
|
|
for _, f := range files {
|
|
|
|
if f.IsDir() || strings.HasPrefix(f.Name(), ".") {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
path := filepath.Join("testdata", f.Name())
|
|
|
|
name := strings.TrimSuffix(f.Name(), filepath.Ext(f.Name()))
|
|
|
|
t.Run(name, func(t *testing.T) {
|
|
|
|
runTestScript(t, path)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
2015-10-15 16:07:19 +02:00
|
|
|
|
2019-02-04 13:47:34 +01:00
|
|
|
func runTestScript(t *testing.T, file string) {
|
|
|
|
server := newTestServer()
|
rpc: add limit for batch request items and response size (#26681)
This PR adds server-side limits for JSON-RPC batch requests. Before this change, batches
were limited only by processing time. The server would pick calls from the batch and
answer them until the response timeout occurred, then stop processing the remaining batch
items.
Here, we are adding two additional limits which can be configured:
- the 'item limit': batches can have at most N items
- the 'response size limit': batches can contain at most X response bytes
These limits are optional in package rpc. In Geth, we set a default limit of 1000 items
and 25MB response size.
When a batch goes over the limit, an error response is returned to the client. However,
doing this correctly isn't always possible. In JSON-RPC, only method calls with a valid
`id` can be responded to. Since batches may also contain non-call messages or
notifications, the best effort thing we can do to report an error with the batch itself is
reporting the limit violation as an error for the first method call in the batch. If a batch is
too large, but contains only notifications and responses, the error will be reported with
a null `id`.
The RPC client was also changed so it can deal with errors resulting from too large
batches. An older client connected to the server code in this PR could get stuck
until the request timeout occurred when the batch is too large. **Upgrading to a version
of the RPC client containing this change is strongly recommended to avoid timeout issues.**
For some weird reason, when writing the original client implementation, @fjl worked off of
the assumption that responses could be distributed across batches arbitrarily. So for a
batch request containing requests `[A B C]`, the server could respond with `[A B C]` but
also with `[A B] [C]` or even `[A] [B] [C]` and it wouldn't make a difference to the
client.
So in the implementation of BatchCallContext, the client waited for all requests in the
batch individually. If the server didn't respond to some of the requests in the batch, the
client would eventually just time out (if a context was used).
With the addition of batch limits into the server, we anticipate that people will hit this
kind of error way more often. To handle this properly, the client now waits for a single
response batch and expects it to contain all responses to the requests.
---------
Co-authored-by: Felix Lange <fjl@twurst.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-06-13 19:38:58 +08:00
|
|
|
server.SetBatchLimits(4, 100000)
|
2022-05-16 11:59:35 +02:00
|
|
|
content, err := os.ReadFile(file)
|
2019-02-04 13:47:34 +01:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
2016-03-14 09:38:54 +01:00
|
|
|
}
|
2015-10-15 16:07:19 +02:00
|
|
|
|
2016-03-14 09:38:54 +01:00
|
|
|
clientConn, serverConn := net.Pipe()
|
|
|
|
defer clientConn.Close()
|
2019-11-18 09:40:59 +01:00
|
|
|
go server.ServeCodec(NewCodec(serverConn), 0)
|
2019-02-04 13:47:34 +01:00
|
|
|
readbuf := bufio.NewReader(clientConn)
|
|
|
|
for _, line := range strings.Split(string(content), "\n") {
|
|
|
|
line = strings.TrimSpace(line)
|
|
|
|
switch {
|
|
|
|
case len(line) == 0 || strings.HasPrefix(line, "//"):
|
|
|
|
// skip comments, blank lines
|
|
|
|
continue
|
|
|
|
case strings.HasPrefix(line, "--> "):
|
|
|
|
t.Log(line)
|
|
|
|
// write to connection
|
|
|
|
clientConn.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
|
|
|
if _, err := io.WriteString(clientConn, line[4:]+"\n"); err != nil {
|
|
|
|
t.Fatalf("write error: %v", err)
|
|
|
|
}
|
|
|
|
case strings.HasPrefix(line, "<-- "):
|
|
|
|
t.Log(line)
|
|
|
|
want := line[4:]
|
|
|
|
// read line from connection and compare text
|
|
|
|
clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
|
|
|
|
sent, err := readbuf.ReadString('\n')
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("read error: %v", err)
|
|
|
|
}
|
|
|
|
sent = strings.TrimRight(sent, "\r\n")
|
|
|
|
if sent != want {
|
|
|
|
t.Errorf("wrong line from server\ngot: %s\nwant: %s", sent, want)
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
panic("invalid line in test script: " + line)
|
|
|
|
}
|
2015-10-15 16:07:19 +02:00
|
|
|
}
|
2019-02-04 13:47:34 +01:00
|
|
|
}
|
2015-10-15 16:07:19 +02:00
|
|
|
|
2019-02-04 13:47:34 +01:00
|
|
|
// This test checks that responses are delivered for very short-lived connections that
|
|
|
|
// only carry a single request.
|
|
|
|
func TestServerShortLivedConn(t *testing.T) {
|
|
|
|
server := newTestServer()
|
|
|
|
defer server.Stop()
|
2015-10-15 16:07:19 +02:00
|
|
|
|
2019-02-04 13:47:34 +01:00
|
|
|
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal("can't listen:", err)
|
|
|
|
}
|
|
|
|
defer listener.Close()
|
|
|
|
go server.ServeListener(listener)
|
|
|
|
|
|
|
|
var (
|
|
|
|
request = `{"jsonrpc":"2.0","id":1,"method":"rpc_modules"}` + "\n"
|
|
|
|
wantResp = `{"jsonrpc":"2.0","id":1,"result":{"nftest":"1.0","rpc":"1.0","test":"1.0"}}` + "\n"
|
|
|
|
deadline = time.Now().Add(10 * time.Second)
|
|
|
|
)
|
|
|
|
for i := 0; i < 20; i++ {
|
|
|
|
conn, err := net.Dial("tcp", listener.Addr().String())
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal("can't dial:", err)
|
2015-10-15 16:07:19 +02:00
|
|
|
}
|
2022-03-11 23:24:13 +08:00
|
|
|
|
2019-02-04 13:47:34 +01:00
|
|
|
conn.SetDeadline(deadline)
|
|
|
|
// Write the request, then half-close the connection so the server stops reading.
|
|
|
|
conn.Write([]byte(request))
|
|
|
|
conn.(*net.TCPConn).CloseWrite()
|
|
|
|
// Now try to get the response.
|
|
|
|
buf := make([]byte, 2000)
|
|
|
|
n, err := conn.Read(buf)
|
2022-03-11 23:24:13 +08:00
|
|
|
conn.Close()
|
|
|
|
|
2019-02-04 13:47:34 +01:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal("read error:", err)
|
2015-10-15 16:07:19 +02:00
|
|
|
}
|
2019-02-04 13:47:34 +01:00
|
|
|
if !bytes.Equal(buf[:n], []byte(wantResp)) {
|
|
|
|
t.Fatalf("wrong response: %s", buf[:n])
|
2015-10-15 16:07:19 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
rpc: add limit for batch request items and response size (#26681)
This PR adds server-side limits for JSON-RPC batch requests. Before this change, batches
were limited only by processing time. The server would pick calls from the batch and
answer them until the response timeout occurred, then stop processing the remaining batch
items.
Here, we are adding two additional limits which can be configured:
- the 'item limit': batches can have at most N items
- the 'response size limit': batches can contain at most X response bytes
These limits are optional in package rpc. In Geth, we set a default limit of 1000 items
and 25MB response size.
When a batch goes over the limit, an error response is returned to the client. However,
doing this correctly isn't always possible. In JSON-RPC, only method calls with a valid
`id` can be responded to. Since batches may also contain non-call messages or
notifications, the best effort thing we can do to report an error with the batch itself is
reporting the limit violation as an error for the first method call in the batch. If a batch is
too large, but contains only notifications and responses, the error will be reported with
a null `id`.
The RPC client was also changed so it can deal with errors resulting from too large
batches. An older client connected to the server code in this PR could get stuck
until the request timeout occurred when the batch is too large. **Upgrading to a version
of the RPC client containing this change is strongly recommended to avoid timeout issues.**
For some weird reason, when writing the original client implementation, @fjl worked off of
the assumption that responses could be distributed across batches arbitrarily. So for a
batch request containing requests `[A B C]`, the server could respond with `[A B C]` but
also with `[A B] [C]` or even `[A] [B] [C]` and it wouldn't make a difference to the
client.
So in the implementation of BatchCallContext, the client waited for all requests in the
batch individually. If the server didn't respond to some of the requests in the batch, the
client would eventually just time out (if a context was used).
With the addition of batch limits into the server, we anticipate that people will hit this
kind of error way more often. To handle this properly, the client now waits for a single
response batch and expects it to contain all responses to the requests.
---------
Co-authored-by: Felix Lange <fjl@twurst.com>
Co-authored-by: Martin Holst Swende <martin@swende.se>
2023-06-13 19:38:58 +08:00
|
|
|
|
|
|
|
func TestServerBatchResponseSizeLimit(t *testing.T) {
|
|
|
|
server := newTestServer()
|
|
|
|
defer server.Stop()
|
|
|
|
server.SetBatchLimits(100, 60)
|
|
|
|
var (
|
|
|
|
batch []BatchElem
|
|
|
|
client = DialInProc(server)
|
|
|
|
)
|
|
|
|
for i := 0; i < 5; i++ {
|
|
|
|
batch = append(batch, BatchElem{
|
|
|
|
Method: "test_echo",
|
|
|
|
Args: []any{"x", 1},
|
|
|
|
Result: new(echoResult),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
if err := client.BatchCall(batch); err != nil {
|
|
|
|
t.Fatal("error sending batch:", err)
|
|
|
|
}
|
|
|
|
for i := range batch {
|
|
|
|
// We expect the first two queries to be ok, but after that the size limit takes effect.
|
|
|
|
if i < 2 {
|
|
|
|
if batch[i].Error != nil {
|
|
|
|
t.Fatalf("batch elem %d has unexpected error: %v", i, batch[i].Error)
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// After two, we expect an error.
|
|
|
|
re, ok := batch[i].Error.(Error)
|
|
|
|
if !ok {
|
|
|
|
t.Fatalf("batch elem %d has wrong error: %v", i, batch[i].Error)
|
|
|
|
}
|
|
|
|
wantedCode := errcodeResponseTooLarge
|
|
|
|
if re.ErrorCode() != wantedCode {
|
|
|
|
t.Errorf("batch elem %d wrong error code, have %d want %d", i, re.ErrorCode(), wantedCode)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|