github.com/core-coin/go-core/v2@v2.1.9/p2p/dnsdisc/tree.go (about)

     1  // Copyright 2019 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package dnsdisc
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/base32"
    22  	"encoding/base64"
    23  	"fmt"
    24  	"io"
    25  	"sort"
    26  	"strings"
    27  
    28  	"golang.org/x/crypto/sha3"
    29  
    30  	"github.com/core-coin/go-core/v2/crypto"
    31  	"github.com/core-coin/go-core/v2/p2p/enode"
    32  	"github.com/core-coin/go-core/v2/p2p/enr"
    33  	"github.com/core-coin/go-core/v2/rlp"
    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 *crypto.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 *crypto.PublicKey, signature string) error {
    58  	sig, err := b64format.DecodeString(signature)
    59  	if err != nil || len(sig) != crypto.ExtendedSignatureLength {
    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 *crypto.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.New256()
   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.New256()
   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 *crypto.PublicKey) bool {
   249  	return crypto.VerifySignature(pubkey[:], e.sigHash(), e.sig)
   250  }
   251  
   252  func (e *branchEntry) String() string {
   253  	return branchPrefix + strings.Join(e.children, ",")
   254  }
   255  
   256  func (e *enrEntry) String() string {
   257  	return e.node.String()
   258  }
   259  
   260  func (e *linkEntry) String() string {
   261  	return linkPrefix + e.str
   262  }
   263  
   264  func newLinkEntry(domain string, pubkey *crypto.PublicKey) *linkEntry {
   265  	key := b32format.EncodeToString(pubkey[:])
   266  	str := key + "@" + domain
   267  	return &linkEntry{str, domain, pubkey}
   268  }
   269  
   270  // Entry Parsing
   271  
   272  func parseEntry(e string, validSchemes enr.IdentityScheme) (entry, error) {
   273  	switch {
   274  	case strings.HasPrefix(e, linkPrefix):
   275  		return parseLinkEntry(e)
   276  	case strings.HasPrefix(e, branchPrefix):
   277  		return parseBranch(e)
   278  	case strings.HasPrefix(e, enrPrefix):
   279  		return parseENR(e, validSchemes)
   280  	default:
   281  		return nil, errUnknownEntry
   282  	}
   283  }
   284  
   285  func parseRoot(e string) (rootEntry, error) {
   286  	var eroot, lroot, sig string
   287  	var seq uint
   288  	if _, err := fmt.Sscanf(e, rootPrefix+" e=%s l=%s seq=%d sig=%s", &eroot, &lroot, &seq, &sig); err != nil {
   289  		return rootEntry{}, entryError{"root", errSyntax}
   290  	}
   291  	if !isValidHash(eroot) || !isValidHash(lroot) {
   292  		return rootEntry{}, entryError{"root", errInvalidChild}
   293  	}
   294  	sigb, err := b64format.DecodeString(sig)
   295  	if err != nil || len(sigb) != crypto.ExtendedSignatureLength {
   296  		return rootEntry{}, entryError{"root", errInvalidSig}
   297  	}
   298  	return rootEntry{eroot, lroot, seq, sigb}, nil
   299  }
   300  
   301  func parseLinkEntry(e string) (entry, error) {
   302  	le, err := parseLink(e)
   303  	if err != nil {
   304  		return nil, err
   305  	}
   306  	return le, nil
   307  }
   308  
   309  func parseLink(e string) (*linkEntry, error) {
   310  	if !strings.HasPrefix(e, linkPrefix) {
   311  		return nil, fmt.Errorf("wrong/missing scheme 'enrtree' in URL")
   312  	}
   313  	e = e[len(linkPrefix):]
   314  	pos := strings.IndexByte(e, '@')
   315  	if pos == -1 {
   316  		return nil, entryError{"link", errNoPubkey}
   317  	}
   318  	keystring, domain := e[:pos], e[pos+1:]
   319  	keybytes, err := b32format.DecodeString(keystring)
   320  	if err != nil {
   321  		return nil, entryError{"link", errBadPubkey}
   322  	}
   323  	key, err := crypto.UnmarshalPubKey(keybytes)
   324  	if err != nil {
   325  		return nil, entryError{"link", errBadPubkey}
   326  	}
   327  	return &linkEntry{e, domain, key}, nil
   328  }
   329  
   330  func parseBranch(e string) (entry, error) {
   331  	e = e[len(branchPrefix):]
   332  	if e == "" {
   333  		return &branchEntry{}, nil // empty entry is OK
   334  	}
   335  	hashes := make([]string, 0, strings.Count(e, ","))
   336  	for _, c := range strings.Split(e, ",") {
   337  		if !isValidHash(c) {
   338  			return nil, entryError{"branch", errInvalidChild}
   339  		}
   340  		hashes = append(hashes, c)
   341  	}
   342  	return &branchEntry{hashes}, nil
   343  }
   344  
   345  func parseENR(e string, validSchemes enr.IdentityScheme) (entry, error) {
   346  	e = e[len(enrPrefix):]
   347  	enc, err := b64format.DecodeString(e)
   348  	if err != nil {
   349  		return nil, entryError{"enr", errInvalidENR}
   350  	}
   351  	var rec enr.Record
   352  	if err := rlp.DecodeBytes(enc, &rec); err != nil {
   353  		return nil, entryError{"enr", err}
   354  	}
   355  	n, err := enode.New(validSchemes, &rec)
   356  	if err != nil {
   357  		return nil, entryError{"enr", err}
   358  	}
   359  	return &enrEntry{n}, nil
   360  }
   361  
   362  func isValidHash(s string) bool {
   363  	dlen := b32format.DecodedLen(len(s))
   364  	if dlen < minHashLength || dlen > 32 || strings.ContainsAny(s, "\n\r") {
   365  		return false
   366  	}
   367  	buf := make([]byte, 32)
   368  	_, err := b32format.Decode(buf, []byte(s))
   369  	return err == nil
   370  }
   371  
   372  // truncateHash truncates the given base32 hash string to the minimum acceptable length.
   373  func truncateHash(hash string) string {
   374  	maxLen := b32format.EncodedLen(minHashLength)
   375  	if len(hash) < maxLen {
   376  		panic(fmt.Errorf("dnsdisc: hash %q is too short", hash))
   377  	}
   378  	return hash[:maxLen]
   379  }
   380  
   381  // URL encoding
   382  
   383  // ParseURL parses an enrtree:// URL and returns its components.
   384  func ParseURL(url string) (domain string, pubkey *crypto.PublicKey, err error) {
   385  	le, err := parseLink(url)
   386  	if err != nil {
   387  		return "", nil, err
   388  	}
   389  	return le.domain, le.pubkey, nil
   390  }