github.com/MetalBlockchain/subnet-evm@v0.6.3/rpc/server_test.go (about)

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