github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/p2p/dnsdisc/tree.go (about)

     1  // Copyright 2018 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 dnsdisc
    18  
    19  import (
    20  	"bytes"
    21  	"crypto/ecdsa"
    22  	"encoding/base32"
    23  	"encoding/base64"
    24  	"fmt"
    25  	"io"
    26  	"sort"
    27  	"strings"
    28  
    29  	"github.com/kisexp/xdchain/crypto"
    30  	"github.com/kisexp/xdchain/p2p/enode"
    31  	"github.com/kisexp/xdchain/p2p/enr"
    32  	"github.com/kisexp/xdchain/rlp"
    33  	"golang.org/x/crypto/sha3"
    34  )
    35  
    36  // Tree is a merkle tree of node records.
    37  type Tree struct {
    38  	root    *rootEntry
    39  	entries map[string]entry
    40  }
    41  
    42  // Sign signs the tree with the given private key and sets the sequence number.
    43  func (t *Tree) Sign(key *ecdsa.PrivateKey, domain string) (url string, err error) {
    44  	root := *t.root
    45  	sig, err := crypto.Sign(root.sigHash(), key)
    46  	if err != nil {
    47  		return "", err
    48  	}
    49  	root.sig = sig
    50  	t.root = &root
    51  	link := newLinkEntry(domain, &key.PublicKey)
    52  	return link.String(), nil
    53  }
    54  
    55  // SetSignature verifies the given signature and assigns it as the tree's current
    56  // signature if valid.
    57  func (t *Tree) SetSignature(pubkey *ecdsa.PublicKey, signature string) error {
    58  	sig, err := b64format.DecodeString(signature)
    59  	if err != nil || len(sig) != crypto.SignatureLength {
    60  		return errInvalidSig
    61  	}
    62  	root := *t.root
    63  	root.sig = sig
    64  	if !root.verifySignature(pubkey) {
    65  		return errInvalidSig
    66  	}
    67  	t.root = &root
    68  	return nil
    69  }
    70  
    71  // Seq returns the sequence number of the tree.
    72  func (t *Tree) Seq() uint {
    73  	return t.root.seq
    74  }
    75  
    76  // Signature returns the signature of the tree.
    77  func (t *Tree) Signature() string {
    78  	return b64format.EncodeToString(t.root.sig)
    79  }
    80  
    81  // ToTXT returns all DNS TXT records required for the tree.
    82  func (t *Tree) ToTXT(domain string) map[string]string {
    83  	records := map[string]string{domain: t.root.String()}
    84  	for _, e := range t.entries {
    85  		sd := subdomain(e)
    86  		if domain != "" {
    87  			sd = sd + "." + domain
    88  		}
    89  		records[sd] = e.String()
    90  	}
    91  	return records
    92  }
    93  
    94  // Links returns all links contained in the tree.
    95  func (t *Tree) Links() []string {
    96  	var links []string
    97  	for _, e := range t.entries {
    98  		if le, ok := e.(*linkEntry); ok {
    99  			links = append(links, le.String())
   100  		}
   101  	}
   102  	return links
   103  }
   104  
   105  // Nodes returns all nodes contained in the tree.
   106  func (t *Tree) Nodes() []*enode.Node {
   107  	var nodes []*enode.Node
   108  	for _, e := range t.entries {
   109  		if ee, ok := e.(*enrEntry); ok {
   110  			nodes = append(nodes, ee.node)
   111  		}
   112  	}
   113  	return nodes
   114  }
   115  
   116  const (
   117  	hashAbbrev    = 16
   118  	maxChildren   = 300 / hashAbbrev * (13 / 8)
   119  	minHashLength = 12
   120  )
   121  
   122  // MakeTree creates a tree containing the given nodes and links.
   123  func MakeTree(seq uint, nodes []*enode.Node, links []string) (*Tree, error) {
   124  	// Sort records by ID and ensure all nodes have a valid record.
   125  	records := make([]*enode.Node, len(nodes))
   126  
   127  	copy(records, nodes)
   128  	sortByID(records)
   129  	for _, n := range records {
   130  		if len(n.Record().Signature()) == 0 {
   131  			return nil, fmt.Errorf("can't add node %v: unsigned node record", n.ID())
   132  		}
   133  	}
   134  
   135  	// Create the leaf list.
   136  	enrEntries := make([]entry, len(records))
   137  	for i, r := range records {
   138  		enrEntries[i] = &enrEntry{r}
   139  	}
   140  	linkEntries := make([]entry, len(links))
   141  	for i, l := range links {
   142  		le, err := parseLink(l)
   143  		if err != nil {
   144  			return nil, err
   145  		}
   146  		linkEntries[i] = le
   147  	}
   148  
   149  	// Create intermediate nodes.
   150  	t := &Tree{entries: make(map[string]entry)}
   151  	eroot := t.build(enrEntries)
   152  	t.entries[subdomain(eroot)] = eroot
   153  	lroot := t.build(linkEntries)
   154  	t.entries[subdomain(lroot)] = lroot
   155  	t.root = &rootEntry{seq: seq, eroot: subdomain(eroot), lroot: subdomain(lroot)}
   156  	return t, nil
   157  }
   158  
   159  func (t *Tree) build(entries []entry) entry {
   160  	if len(entries) == 1 {
   161  		return entries[0]
   162  	}
   163  	if len(entries) <= maxChildren {
   164  		hashes := make([]string, len(entries))
   165  		for i, e := range entries {
   166  			hashes[i] = subdomain(e)
   167  			t.entries[hashes[i]] = e
   168  		}
   169  		return &branchEntry{hashes}
   170  	}
   171  	var subtrees []entry
   172  	for len(entries) > 0 {
   173  		n := maxChildren
   174  		if len(entries) < n {
   175  			n = len(entries)
   176  		}
   177  		sub := t.build(entries[:n])
   178  		entries = entries[n:]
   179  		subtrees = append(subtrees, sub)
   180  		t.entries[subdomain(sub)] = sub
   181  	}
   182  	return t.build(subtrees)
   183  }
   184  
   185  func sortByID(nodes []*enode.Node) []*enode.Node {
   186  	sort.Slice(nodes, func(i, j int) bool {
   187  		return bytes.Compare(nodes[i].ID().Bytes(), nodes[j].ID().Bytes()) < 0
   188  	})
   189  	return nodes
   190  }
   191  
   192  // Entry Types
   193  
   194  type entry interface {
   195  	fmt.Stringer
   196  }
   197  
   198  type (
   199  	rootEntry struct {
   200  		eroot string
   201  		lroot string
   202  		seq   uint
   203  		sig   []byte
   204  	}
   205  	branchEntry struct {
   206  		children []string
   207  	}
   208  	enrEntry struct {
   209  		node *enode.Node
   210  	}
   211  	linkEntry struct {
   212  		str    string
   213  		domain string
   214  		pubkey *ecdsa.PublicKey
   215  	}
   216  )
   217  
   218  // Entry Encoding
   219  
   220  var (
   221  	b32format = base32.StdEncoding.WithPadding(base32.NoPadding)
   222  	b64format = base64.RawURLEncoding
   223  )
   224  
   225  const (
   226  	rootPrefix   = "enrtree-root:v1"
   227  	linkPrefix   = "enrtree://"
   228  	branchPrefix = "enrtree-branch:"
   229  	enrPrefix    = "enr:"
   230  )
   231  
   232  func subdomain(e entry) string {
   233  	h := sha3.NewLegacyKeccak256()
   234  	io.WriteString(h, e.String())
   235  	return b32format.EncodeToString(h.Sum(nil)[:16])
   236  }
   237  
   238  func (e *rootEntry) String() string {
   239  	return fmt.Sprintf(rootPrefix+" e=%s l=%s seq=%d sig=%s", e.eroot, e.lroot, e.seq, b64format.EncodeToString(e.sig))
   240  }
   241  
   242  func (e *rootEntry) sigHash() []byte {
   243  	h := sha3.NewLegacyKeccak256()
   244  	fmt.Fprintf(h, rootPrefix+" e=%s l=%s seq=%d", e.eroot, e.lroot, e.seq)
   245  	return h.Sum(nil)
   246  }
   247  
   248  func (e *rootEntry) verifySignature(pubkey *ecdsa.PublicKey) bool {
   249  	sig := e.sig[:crypto.RecoveryIDOffset] // remove recovery id
   250  	enckey := crypto.FromECDSAPub(pubkey)
   251  	return crypto.VerifySignature(enckey, e.sigHash(), sig)
   252  }
   253  
   254  func (e *branchEntry) String() string {
   255  	return branchPrefix + strings.Join(e.children, ",")
   256  }
   257  
   258  func (e *enrEntry) String() string {
   259  	return e.node.String()
   260  }
   261  
   262  func (e *linkEntry) String() string {
   263  	return linkPrefix + e.str
   264  }
   265  
   266  func newLinkEntry(domain string, pubkey *ecdsa.PublicKey) *linkEntry {
   267  	key := b32format.EncodeToString(crypto.CompressPubkey(pubkey))
   268  	str := key + "@" + domain
   269  	return &linkEntry{str, domain, pubkey}
   270  }
   271  
   272  // Entry Parsing
   273  
   274  func parseEntry(e string, validSchemes enr.IdentityScheme) (entry, error) {
   275  	switch {
   276  	case strings.HasPrefix(e, linkPrefix):
   277  		return parseLinkEntry(e)
   278  	case strings.HasPrefix(e, branchPrefix):
   279  		return parseBranch(e)
   280  	case strings.HasPrefix(e, enrPrefix):
   281  		return parseENR(e, validSchemes)
   282  	default:
   283  		return nil, errUnknownEntry
   284  	}
   285  }
   286  
   287  func parseRoot(e string) (rootEntry, error) {
   288  	var eroot, lroot, sig string
   289  	var seq uint
   290  	if _, err := fmt.Sscanf(e, rootPrefix+" e=%s l=%s seq=%d sig=%s", &eroot, &lroot, &seq, &sig); err != nil {
   291  		return rootEntry{}, entryError{"root", errSyntax}
   292  	}
   293  	if !isValidHash(eroot) || !isValidHash(lroot) {
   294  		return rootEntry{}, entryError{"root", errInvalidChild}
   295  	}
   296  	sigb, err := b64format.DecodeString(sig)
   297  	if err != nil || len(sigb) != crypto.SignatureLength {
   298  		return rootEntry{}, entryError{"root", errInvalidSig}
   299  	}
   300  	return rootEntry{eroot, lroot, seq, sigb}, nil
   301  }
   302  
   303  func parseLinkEntry(e string) (entry, error) {
   304  	le, err := parseLink(e)
   305  	if err != nil {
   306  		return nil, err
   307  	}
   308  	return le, nil
   309  }
   310  
   311  func parseLink(e string) (*linkEntry, error) {
   312  	if !strings.HasPrefix(e, linkPrefix) {
   313  		return nil, fmt.Errorf("wrong/missing scheme 'enrtree' in URL")
   314  	}
   315  	e = e[len(linkPrefix):]
   316  	pos := strings.IndexByte(e, '@')
   317  	if pos == -1 {
   318  		return nil, entryError{"link", errNoPubkey}
   319  	}
   320  	keystring, domain := e[:pos], e[pos+1:]
   321  	keybytes, err := b32format.DecodeString(keystring)
   322  	if err != nil {
   323  		return nil, entryError{"link", errBadPubkey}
   324  	}
   325  	key, err := crypto.DecompressPubkey(keybytes)
   326  	if err != nil {
   327  		return nil, entryError{"link", errBadPubkey}
   328  	}
   329  	return &linkEntry{e, domain, key}, nil
   330  }
   331  
   332  func parseBranch(e string) (entry, error) {
   333  	e = e[len(branchPrefix):]
   334  	if e == "" {
   335  		return &branchEntry{}, nil // empty entry is OK
   336  	}
   337  	hashes := make([]string, 0, strings.Count(e, ","))
   338  	for _, c := range strings.Split(e, ",") {
   339  		if !isValidHash(c) {
   340  			return nil, entryError{"branch", errInvalidChild}
   341  		}
   342  		hashes = append(hashes, c)
   343  	}
   344  	return &branchEntry{hashes}, nil
   345  }
   346  
   347  func parseENR(e string, validSchemes enr.IdentityScheme) (entry, error) {
   348  	e = e[len(enrPrefix):]
   349  	enc, err := b64format.DecodeString(e)
   350  	if err != nil {
   351  		return nil, entryError{"enr", errInvalidENR}
   352  	}
   353  	var rec enr.Record
   354  	if err := rlp.DecodeBytes(enc, &rec); err != nil {
   355  		return nil, entryError{"enr", err}
   356  	}
   357  	n, err := enode.New(validSchemes, &rec)
   358  	if err != nil {
   359  		return nil, entryError{"enr", err}
   360  	}
   361  	return &enrEntry{n}, nil
   362  }
   363  
   364  func isValidHash(s string) bool {
   365  	dlen := b32format.DecodedLen(len(s))
   366  	if dlen < minHashLength || dlen > 32 || strings.ContainsAny(s, "\n\r") {
   367  		return false
   368  	}
   369  	buf := make([]byte, 32)
   370  	_, err := b32format.Decode(buf, []byte(s))
   371  	return err == nil
   372  }
   373  
   374  // truncateHash truncates the given base32 hash string to the minimum acceptable length.
   375  func truncateHash(hash string) string {
   376  	maxLen := b32format.EncodedLen(minHashLength)
   377  	if len(hash) < maxLen {
   378  		panic(fmt.Errorf("dnsdisc: hash %q is too short", hash))
   379  	}
   380  	return hash[:maxLen]
   381  }
   382  
   383  // URL encoding
   384  
   385  // ParseURL parses an enrtree:// URL and returns its components.
   386  func ParseURL(url string) (domain string, pubkey *ecdsa.PublicKey, err error) {
   387  	le, err := parseLink(url)
   388  	if err != nil {
   389  		return "", nil, err
   390  	}
   391  	return le.domain, le.pubkey, nil
   392  }