github.com/ethereum/go-ethereum@v1.16.1/core/stateless/encoding.go (about)

     1  // Copyright 2024 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 stateless
    18  
    19  import (
    20  	"io"
    21  
    22  	"github.com/ethereum/go-ethereum/core/types"
    23  	"github.com/ethereum/go-ethereum/rlp"
    24  )
    25  
    26  // toExtWitness converts our internal witness representation to the consensus one.
    27  func (w *Witness) toExtWitness() *extWitness {
    28  	ext := &extWitness{
    29  		Headers: w.Headers,
    30  	}
    31  	ext.Codes = make([][]byte, 0, len(w.Codes))
    32  	for code := range w.Codes {
    33  		ext.Codes = append(ext.Codes, []byte(code))
    34  	}
    35  	ext.State = make([][]byte, 0, len(w.State))
    36  	for node := range w.State {
    37  		ext.State = append(ext.State, []byte(node))
    38  	}
    39  	return ext
    40  }
    41  
    42  // fromExtWitness converts the consensus witness format into our internal one.
    43  func (w *Witness) fromExtWitness(ext *extWitness) error {
    44  	w.Headers = ext.Headers
    45  
    46  	w.Codes = make(map[string]struct{}, len(ext.Codes))
    47  	for _, code := range ext.Codes {
    48  		w.Codes[string(code)] = struct{}{}
    49  	}
    50  	w.State = make(map[string]struct{}, len(ext.State))
    51  	for _, node := range ext.State {
    52  		w.State[string(node)] = struct{}{}
    53  	}
    54  	return nil
    55  }
    56  
    57  // EncodeRLP serializes a witness as RLP.
    58  func (w *Witness) EncodeRLP(wr io.Writer) error {
    59  	return rlp.Encode(wr, w.toExtWitness())
    60  }
    61  
    62  // DecodeRLP decodes a witness from RLP.
    63  func (w *Witness) DecodeRLP(s *rlp.Stream) error {
    64  	var ext extWitness
    65  	if err := s.Decode(&ext); err != nil {
    66  		return err
    67  	}
    68  	return w.fromExtWitness(&ext)
    69  }
    70  
    71  // extWitness is a witness RLP encoding for transferring across clients.
    72  type extWitness struct {
    73  	Headers []*types.Header
    74  	Codes   [][]byte
    75  	State   [][]byte
    76  }