github.com/ethereum/go-ethereum@v1.14.3/rpc/server_test.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rpc
    18  
    19  import (
    20  	"bufio"
    21  	"bytes"
    22  	"io"
    23  	"net"
    24  	"os"
    25  	"path/filepath"
    26  	"strings"
    27  	"testing"
    28  	"time"
    29  )
    30  
    31  func TestServerRegisterName(t *testing.T) {
    32  	server := NewServer()
    33  	service := new(testService)
    34  
    35  	svcName := "test"
    36  	if err := server.RegisterName(svcName, service); err != nil {
    37  		t.Fatalf("%v", err)
    38  	}
    39  
    40  	if len(server.services.services) != 2 {
    41  		t.Fatalf("Expected 2 service entries, got %d", len(server.services.services))
    42  	}
    43  
    44  	svc, ok := server.services.services[svcName]
    45  	if !ok {
    46  		t.Fatalf("Expected service %s to be registered", svcName)
    47  	}
    48  
    49  	wantCallbacks := 14
    50  	if len(svc.callbacks) != wantCallbacks {
    51  		t.Errorf("Expected %d callbacks for service 'service', got %d", wantCallbacks, len(svc.callbacks))
    52  	}
    53  }
    54  
    55  func TestServer(t *testing.T) {
    56  	files, err := os.ReadDir("testdata")
    57  	if err != nil {
    58  		t.Fatal("where'd my testdata go?")
    59  	}
    60  	for _, f := range files {
    61  		if f.IsDir() || strings.HasPrefix(f.Name(), ".") {
    62  			continue
    63  		}
    64  		path := filepath.Join("testdata", f.Name())
    65  		name := strings.TrimSuffix(f.Name(), filepath.Ext(f.Name()))
    66  		t.Run(name, func(t *testing.T) {
    67  			runTestScript(t, path)
    68  		})
    69  	}
    70  }
    71  
    72  func runTestScript(t *testing.T, file string) {
    73  	server := newTestServer()
    74  	server.SetBatchLimits(4, 100000)
    75  	content, err := os.ReadFile(file)
    76  	if err != nil {
    77  		t.Fatal(err)
    78  	}
    79  
    80  	clientConn, serverConn := net.Pipe()
    81  	defer clientConn.Close()
    82  	go server.ServeCodec(NewCodec(serverConn), 0)
    83  	readbuf := bufio.NewReader(clientConn)
    84  	for _, line := range strings.Split(string(content), "\n") {
    85  		line = strings.TrimSpace(line)
    86  		switch {
    87  		case len(line) == 0 || strings.HasPrefix(line, "//"):
    88  			// skip comments, blank lines
    89  			continue
    90  		case strings.HasPrefix(line, "--> "):
    91  			t.Log(line)
    92  			// write to connection
    93  			clientConn.SetWriteDeadline(time.Now().Add(5 * time.Second))
    94  			if _, err := io.WriteString(clientConn, line[4:]+"\n"); err != nil {
    95  				t.Fatalf("write error: %v", err)
    96  			}
    97  		case strings.HasPrefix(line, "<-- "):
    98  			t.Log(line)
    99  			want := line[4:]
   100  			// read line from connection and compare text
   101  			clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
   102  			sent, err := readbuf.ReadString('\n')
   103  			if err != nil {
   104  				t.Fatalf("read error: %v", err)
   105  			}
   106  			sent = strings.TrimRight(sent, "\r\n")
   107  			if sent != want {
   108  				t.Errorf("wrong line from server\ngot:  %s\nwant: %s", sent, want)
   109  			}
   110  		default:
   111  			panic("invalid line in test script: " + line)
   112  		}
   113  	}
   114  }
   115  
   116  // This test checks that responses are delivered for very short-lived connections that
   117  // only carry a single request.
   118  func TestServerShortLivedConn(t *testing.T) {
   119  	server := newTestServer()
   120  	defer server.Stop()
   121  
   122  	listener, err := net.Listen("tcp", "127.0.0.1:0")
   123  	if err != nil {
   124  		t.Fatal("can't listen:", err)
   125  	}
   126  	defer listener.Close()
   127  	go server.ServeListener(listener)
   128  
   129  	var (
   130  		request  = `{"jsonrpc":"2.0","id":1,"method":"rpc_modules"}` + "\n"
   131  		wantResp = `{"jsonrpc":"2.0","id":1,"result":{"nftest":"1.0","rpc":"1.0","test":"1.0"}}` + "\n"
   132  		deadline = time.Now().Add(10 * time.Second)
   133  	)
   134  	for i := 0; i < 20; i++ {
   135  		conn, err := net.Dial("tcp", listener.Addr().String())
   136  		if err != nil {
   137  			t.Fatal("can't dial:", err)
   138  		}
   139  
   140  		conn.SetDeadline(deadline)
   141  		// Write the request, then half-close the connection so the server stops reading.
   142  		conn.Write([]byte(request))
   143  		conn.(*net.TCPConn).CloseWrite()
   144  		// Now try to get the response.
   145  		buf := make([]byte, 2000)
   146  		n, err := conn.Read(buf)
   147  		conn.Close()
   148  
   149  		if err != nil {
   150  			t.Fatal("read error:", err)
   151  		}
   152  		if !bytes.Equal(buf[:n], []byte(wantResp)) {
   153  			t.Fatalf("wrong response: %s", buf[:n])
   154  		}
   155  	}
   156  }
   157  
   158  func TestServerBatchResponseSizeLimit(t *testing.T) {
   159  	server := newTestServer()
   160  	defer server.Stop()
   161  	server.SetBatchLimits(100, 60)
   162  	var (
   163  		batch  []BatchElem
   164  		client = DialInProc(server)
   165  	)
   166  	for i := 0; i < 5; i++ {
   167  		batch = append(batch, BatchElem{
   168  			Method: "test_echo",
   169  			Args:   []any{"x", 1},
   170  			Result: new(echoResult),
   171  		})
   172  	}
   173  	if err := client.BatchCall(batch); err != nil {
   174  		t.Fatal("error sending batch:", err)
   175  	}
   176  	for i := range batch {
   177  		// We expect the first two queries to be ok, but after that the size limit takes effect.
   178  		if i < 2 {
   179  			if batch[i].Error != nil {
   180  				t.Fatalf("batch elem %d has unexpected error: %v", i, batch[i].Error)
   181  			}
   182  			continue
   183  		}
   184  		// After two, we expect an error.
   185  		re, ok := batch[i].Error.(Error)
   186  		if !ok {
   187  			t.Fatalf("batch elem %d has wrong error: %v", i, batch[i].Error)
   188  		}
   189  		wantedCode := errcodeResponseTooLarge
   190  		if re.ErrorCode() != wantedCode {
   191  			t.Errorf("batch elem %d wrong error code, have %d want %d", i, re.ErrorCode(), wantedCode)
   192  		}
   193  	}
   194  }