github.com/EgonCoin/EgonChain@v1.10.16/p2p/enr/enr.go (about)

     1  // Copyright 2017 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 enr implements Ethereum Node Records as defined in EIP-778. A node record holds
    18  // arbitrary information about a node on the peer-to-peer network. Node information is
    19  // stored in key/value pairs. To store and retrieve key/values in a record, use the Entry
    20  // interface.
    21  //
    22  // Signature Handling
    23  //
    24  // Records must be signed before transmitting them to another node.
    25  //
    26  // Decoding a record doesn't check its signature. Code working with records from an
    27  // untrusted source must always verify two things: that the record uses an identity scheme
    28  // deemed secure, and that the signature is valid according to the declared scheme.
    29  //
    30  // When creating a record, set the entries you want and use a signing function provided by
    31  // the identity scheme to add the signature. Modifying a record invalidates the signature.
    32  //
    33  // Package enr supports the "secp256k1-keccak" identity scheme.
    34  package enr
    35  
    36  import (
    37  	"bytes"
    38  	"errors"
    39  	"fmt"
    40  	"io"
    41  	"sort"
    42  
    43  	"github.com/EgonCoin/EgonChain/rlp"
    44  )
    45  
    46  const SizeLimit = 300 // maximum encoded size of a node record in bytes
    47  
    48  var (
    49  	ErrInvalidSig     = errors.New("invalid signature on node record")
    50  	errNotSorted      = errors.New("record key/value pairs are not sorted by key")
    51  	errDuplicateKey   = errors.New("record contains duplicate key")
    52  	errIncompletePair = errors.New("record contains incomplete k/v pair")
    53  	errIncompleteList = errors.New("record contains less than two list elements")
    54  	errTooBig         = fmt.Errorf("record bigger than %d bytes", SizeLimit)
    55  	errEncodeUnsigned = errors.New("can't encode unsigned record")
    56  	errNotFound       = errors.New("no such key in record")
    57  )
    58  
    59  // An IdentityScheme is capable of verifying record signatures and
    60  // deriving node addresses.
    61  type IdentityScheme interface {
    62  	Verify(r *Record, sig []byte) error
    63  	NodeAddr(r *Record) []byte
    64  }
    65  
    66  // SchemeMap is a registry of named identity schemes.
    67  type SchemeMap map[string]IdentityScheme
    68  
    69  func (m SchemeMap) Verify(r *Record, sig []byte) error {
    70  	s := m[r.IdentityScheme()]
    71  	if s == nil {
    72  		return ErrInvalidSig
    73  	}
    74  	return s.Verify(r, sig)
    75  }
    76  
    77  func (m SchemeMap) NodeAddr(r *Record) []byte {
    78  	s := m[r.IdentityScheme()]
    79  	if s == nil {
    80  		return nil
    81  	}
    82  	return s.NodeAddr(r)
    83  }
    84  
    85  // Record represents a node record. The zero value is an empty record.
    86  type Record struct {
    87  	seq       uint64 // sequence number
    88  	signature []byte // the signature
    89  	raw       []byte // RLP encoded record
    90  	pairs     []pair // sorted list of all key/value pairs
    91  }
    92  
    93  // pair is a key/value pair in a record.
    94  type pair struct {
    95  	k string
    96  	v rlp.RawValue
    97  }
    98  
    99  // Seq returns the sequence number.
   100  func (r *Record) Seq() uint64 {
   101  	return r.seq
   102  }
   103  
   104  // SetSeq updates the record sequence number. This invalidates any signature on the record.
   105  // Calling SetSeq is usually not required because setting any key in a signed record
   106  // increments the sequence number.
   107  func (r *Record) SetSeq(s uint64) {
   108  	r.signature = nil
   109  	r.raw = nil
   110  	r.seq = s
   111  }
   112  
   113  // Load retrieves the value of a key/value pair. The given Entry must be a pointer and will
   114  // be set to the value of the entry in the record.
   115  //
   116  // Errors returned by Load are wrapped in KeyError. You can distinguish decoding errors
   117  // from missing keys using the IsNotFound function.
   118  func (r *Record) Load(e Entry) error {
   119  	i := sort.Search(len(r.pairs), func(i int) bool { return r.pairs[i].k >= e.ENRKey() })
   120  	if i < len(r.pairs) && r.pairs[i].k == e.ENRKey() {
   121  		if err := rlp.DecodeBytes(r.pairs[i].v, e); err != nil {
   122  			return &KeyError{Key: e.ENRKey(), Err: err}
   123  		}
   124  		return nil
   125  	}
   126  	return &KeyError{Key: e.ENRKey(), Err: errNotFound}
   127  }
   128  
   129  // Set adds or updates the given entry in the record. It panics if the value can't be
   130  // encoded. If the record is signed, Set increments the sequence number and invalidates
   131  // the sequence number.
   132  func (r *Record) Set(e Entry) {
   133  	blob, err := rlp.EncodeToBytes(e)
   134  	if err != nil {
   135  		panic(fmt.Errorf("enr: can't encode %s: %v", e.ENRKey(), err))
   136  	}
   137  	r.invalidate()
   138  
   139  	pairs := make([]pair, len(r.pairs))
   140  	copy(pairs, r.pairs)
   141  	i := sort.Search(len(pairs), func(i int) bool { return pairs[i].k >= e.ENRKey() })
   142  	switch {
   143  	case i < len(pairs) && pairs[i].k == e.ENRKey():
   144  		// element is present at r.pairs[i]
   145  		pairs[i].v = blob
   146  	case i < len(r.pairs):
   147  		// insert pair before i-th elem
   148  		el := pair{e.ENRKey(), blob}
   149  		pairs = append(pairs, pair{})
   150  		copy(pairs[i+1:], pairs[i:])
   151  		pairs[i] = el
   152  	default:
   153  		// element should be placed at the end of r.pairs
   154  		pairs = append(pairs, pair{e.ENRKey(), blob})
   155  	}
   156  	r.pairs = pairs
   157  }
   158  
   159  func (r *Record) invalidate() {
   160  	if r.signature != nil {
   161  		r.seq++
   162  	}
   163  	r.signature = nil
   164  	r.raw = nil
   165  }
   166  
   167  // Signature returns the signature of the record.
   168  func (r *Record) Signature() []byte {
   169  	if r.signature == nil {
   170  		return nil
   171  	}
   172  	cpy := make([]byte, len(r.signature))
   173  	copy(cpy, r.signature)
   174  	return cpy
   175  }
   176  
   177  // EncodeRLP implements rlp.Encoder. Encoding fails if
   178  // the record is unsigned.
   179  func (r Record) EncodeRLP(w io.Writer) error {
   180  	if r.signature == nil {
   181  		return errEncodeUnsigned
   182  	}
   183  	_, err := w.Write(r.raw)
   184  	return err
   185  }
   186  
   187  // DecodeRLP implements rlp.Decoder. Decoding doesn't verify the signature.
   188  func (r *Record) DecodeRLP(s *rlp.Stream) error {
   189  	dec, raw, err := decodeRecord(s)
   190  	if err != nil {
   191  		return err
   192  	}
   193  	*r = dec
   194  	r.raw = raw
   195  	return nil
   196  }
   197  
   198  func decodeRecord(s *rlp.Stream) (dec Record, raw []byte, err error) {
   199  	raw, err = s.Raw()
   200  	if err != nil {
   201  		return dec, raw, err
   202  	}
   203  	if len(raw) > SizeLimit {
   204  		return dec, raw, errTooBig
   205  	}
   206  
   207  	// Decode the RLP container.
   208  	s = rlp.NewStream(bytes.NewReader(raw), 0)
   209  	if _, err := s.List(); err != nil {
   210  		return dec, raw, err
   211  	}
   212  	if err = s.Decode(&dec.signature); err != nil {
   213  		if err == rlp.EOL {
   214  			err = errIncompleteList
   215  		}
   216  		return dec, raw, err
   217  	}
   218  	if err = s.Decode(&dec.seq); err != nil {
   219  		if err == rlp.EOL {
   220  			err = errIncompleteList
   221  		}
   222  		return dec, raw, err
   223  	}
   224  	// The rest of the record contains sorted k/v pairs.
   225  	var prevkey string
   226  	for i := 0; ; i++ {
   227  		var kv pair
   228  		if err := s.Decode(&kv.k); err != nil {
   229  			if err == rlp.EOL {
   230  				break
   231  			}
   232  			return dec, raw, err
   233  		}
   234  		if err := s.Decode(&kv.v); err != nil {
   235  			if err == rlp.EOL {
   236  				return dec, raw, errIncompletePair
   237  			}
   238  			return dec, raw, err
   239  		}
   240  		if i > 0 {
   241  			if kv.k == prevkey {
   242  				return dec, raw, errDuplicateKey
   243  			}
   244  			if kv.k < prevkey {
   245  				return dec, raw, errNotSorted
   246  			}
   247  		}
   248  		dec.pairs = append(dec.pairs, kv)
   249  		prevkey = kv.k
   250  	}
   251  	return dec, raw, s.ListEnd()
   252  }
   253  
   254  // IdentityScheme returns the name of the identity scheme in the record.
   255  func (r *Record) IdentityScheme() string {
   256  	var id ID
   257  	r.Load(&id)
   258  	return string(id)
   259  }
   260  
   261  // VerifySignature checks whether the record is signed using the given identity scheme.
   262  func (r *Record) VerifySignature(s IdentityScheme) error {
   263  	return s.Verify(r, r.signature)
   264  }
   265  
   266  // SetSig sets the record signature. It returns an error if the encoded record is larger
   267  // than the size limit or if the signature is invalid according to the passed scheme.
   268  //
   269  // You can also use SetSig to remove the signature explicitly by passing a nil scheme
   270  // and signature.
   271  //
   272  // SetSig panics when either the scheme or the signature (but not both) are nil.
   273  func (r *Record) SetSig(s IdentityScheme, sig []byte) error {
   274  	switch {
   275  	// Prevent storing invalid data.
   276  	case s == nil && sig != nil:
   277  		panic("enr: invalid call to SetSig with non-nil signature but nil scheme")
   278  	case s != nil && sig == nil:
   279  		panic("enr: invalid call to SetSig with nil signature but non-nil scheme")
   280  	// Verify if we have a scheme.
   281  	case s != nil:
   282  		if err := s.Verify(r, sig); err != nil {
   283  			return err
   284  		}
   285  		raw, err := r.encode(sig)
   286  		if err != nil {
   287  			return err
   288  		}
   289  		r.signature, r.raw = sig, raw
   290  	// Reset otherwise.
   291  	default:
   292  		r.signature, r.raw = nil, nil
   293  	}
   294  	return nil
   295  }
   296  
   297  // AppendElements appends the sequence number and entries to the given slice.
   298  func (r *Record) AppendElements(list []interface{}) []interface{} {
   299  	list = append(list, r.seq)
   300  	for _, p := range r.pairs {
   301  		list = append(list, p.k, p.v)
   302  	}
   303  	return list
   304  }
   305  
   306  func (r *Record) encode(sig []byte) (raw []byte, err error) {
   307  	list := make([]interface{}, 1, 2*len(r.pairs)+2)
   308  	list[0] = sig
   309  	list = r.AppendElements(list)
   310  	if raw, err = rlp.EncodeToBytes(list); err != nil {
   311  		return nil, err
   312  	}
   313  	if len(raw) > SizeLimit {
   314  		return nil, errTooBig
   315  	}
   316  	return raw, nil
   317  }