github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/cmd/devp2p/internal/ethtest/engine.go (about)

     1  // Copyright 2023 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU 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  // go-ethereum 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 General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package ethtest
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  	"io"
    23  	"net/http"
    24  	"os"
    25  	"path/filepath"
    26  	"time"
    27  
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/golang-jwt/jwt/v4"
    30  )
    31  
    32  // EngineClient is a wrapper around engine-related data.
    33  type EngineClient struct {
    34  	url     string
    35  	jwt     [32]byte
    36  	headfcu []byte
    37  }
    38  
    39  // NewEngineClient creates a new engine client.
    40  func NewEngineClient(dir, url, jwt string) (*EngineClient, error) {
    41  	headfcu, err := os.ReadFile(filepath.Join(dir, "headfcu.json"))
    42  	if err != nil {
    43  		return nil, fmt.Errorf("failed to read headfcu: %w", err)
    44  	}
    45  	return &EngineClient{url, common.HexToHash(jwt), headfcu}, nil
    46  }
    47  
    48  // token returns the jwt claim token for authorization.
    49  func (ec *EngineClient) token() string {
    50  	claims := jwt.RegisteredClaims{IssuedAt: jwt.NewNumericDate(time.Now())}
    51  	token, _ := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(ec.jwt[:])
    52  	return token
    53  }
    54  
    55  // sendForkchoiceUpdated sends an fcu for the head of the generated chain.
    56  func (ec *EngineClient) sendForkchoiceUpdated() error {
    57  	var (
    58  		req, _ = http.NewRequest(http.MethodPost, ec.url, io.NopCloser(bytes.NewReader(ec.headfcu)))
    59  		header = make(http.Header)
    60  	)
    61  	// Set header
    62  	header.Set("accept", "application/json")
    63  	header.Set("content-type", "application/json")
    64  	header.Set("Authorization", fmt.Sprintf("Bearer %v", ec.token()))
    65  	req.Header = header
    66  
    67  	_, err := new(http.Client).Do(req)
    68  	return err
    69  }