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