github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/p2p/enode/urlv4.go (about)

     1  // Copyright 2021 The adkgo Authors
     2  // This file is part of the adkgo library (adapted for adkgo from go--ethereum v1.10.8).
     3  //
     4  // the adkgo 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 adkgo 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 adkgo library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package enode
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"encoding/hex"
    22  	"errors"
    23  	"fmt"
    24  	"net"
    25  	"net/url"
    26  	"regexp"
    27  	"strconv"
    28  
    29  	"github.com/aidoskuneen/adk-node/common/math"
    30  	"github.com/aidoskuneen/adk-node/crypto"
    31  	"github.com/aidoskuneen/adk-node/p2p/enr"
    32  )
    33  
    34  var (
    35  	incompleteNodeURL = regexp.MustCompile("(?i)^(?:enode://)?([0-9a-f]+)$")
    36  	lookupIPFunc      = net.LookupIP
    37  )
    38  
    39  // MustParseV4 parses a node URL. It panics if the URL is not valid.
    40  func MustParseV4(rawurl string) *Node {
    41  	n, err := ParseV4(rawurl)
    42  	if err != nil {
    43  		panic("invalid node URL: " + err.Error())
    44  	}
    45  	return n
    46  }
    47  
    48  // ParseV4 parses a node URL.
    49  //
    50  // There are two basic forms of node URLs:
    51  //
    52  //   - incomplete nodes, which only have the public key (node ID)
    53  //   - complete nodes, which contain the public key and IP/Port information
    54  //
    55  // For incomplete nodes, the designator must look like one of these
    56  //
    57  //    enode://<hex node id>
    58  //    <hex node id>
    59  //
    60  // For complete nodes, the node ID is encoded in the username portion
    61  // of the URL, separated from the host by an @ sign. The hostname can
    62  // only be given as an IP address or using DNS domain name.
    63  // The port in the host name section is the TCP listening port. If the
    64  // TCP and UDP (discovery) ports differ, the UDP port is specified as
    65  // query parameter "discport".
    66  //
    67  // In the following example, the node URL describes
    68  // a node with IP address 10.3.58.6, TCP listening port 30303
    69  // and UDP discovery port 30301.
    70  //
    71  //    enode://<hex node id>@10.3.58.6:30303?discport=30301
    72  func ParseV4(rawurl string) (*Node, error) {
    73  	if m := incompleteNodeURL.FindStringSubmatch(rawurl); m != nil {
    74  		id, err := parsePubkey(m[1])
    75  		if err != nil {
    76  			return nil, fmt.Errorf("invalid public key (%v)", err)
    77  		}
    78  		return NewV4(id, nil, 0, 0), nil
    79  	}
    80  	return parseComplete(rawurl)
    81  }
    82  
    83  // NewV4 creates a node from discovery v4 node information. The record
    84  // contained in the node has a zero-length signature.
    85  func NewV4(pubkey *ecdsa.PublicKey, ip net.IP, tcp, udp int) *Node {
    86  	var r enr.Record
    87  	if len(ip) > 0 {
    88  		r.Set(enr.IP(ip))
    89  	}
    90  	if udp != 0 {
    91  		r.Set(enr.UDP(udp))
    92  	}
    93  	if tcp != 0 {
    94  		r.Set(enr.TCP(tcp))
    95  	}
    96  	signV4Compat(&r, pubkey)
    97  	n, err := New(v4CompatID{}, &r)
    98  	if err != nil {
    99  		panic(err)
   100  	}
   101  	return n
   102  }
   103  
   104  // isNewV4 returns true for nodes created by NewV4.
   105  func isNewV4(n *Node) bool {
   106  	var k s256raw
   107  	return n.r.IdentityScheme() == "" && n.r.Load(&k) == nil && len(n.r.Signature()) == 0
   108  }
   109  
   110  func parseComplete(rawurl string) (*Node, error) {
   111  	var (
   112  		id               *ecdsa.PublicKey
   113  		tcpPort, udpPort uint64
   114  	)
   115  	u, err := url.Parse(rawurl)
   116  	if err != nil {
   117  		return nil, err
   118  	}
   119  	if u.Scheme != "enode" {
   120  		return nil, errors.New("invalid URL scheme, want \"enode\"")
   121  	}
   122  	// Parse the Node ID from the user portion.
   123  	if u.User == nil {
   124  		return nil, errors.New("does not contain node ID")
   125  	}
   126  	if id, err = parsePubkey(u.User.String()); err != nil {
   127  		return nil, fmt.Errorf("invalid public key (%v)", err)
   128  	}
   129  	// Parse the IP address.
   130  	ip := net.ParseIP(u.Hostname())
   131  	if ip == nil {
   132  		ips, err := lookupIPFunc(u.Hostname())
   133  		if err != nil {
   134  			return nil, err
   135  		}
   136  		ip = ips[0]
   137  	}
   138  	// Ensure the IP is 4 bytes long for IPv4 addresses.
   139  	if ipv4 := ip.To4(); ipv4 != nil {
   140  		ip = ipv4
   141  	}
   142  	// Parse the port numbers.
   143  	if tcpPort, err = strconv.ParseUint(u.Port(), 10, 16); err != nil {
   144  		return nil, errors.New("invalid port")
   145  	}
   146  	udpPort = tcpPort
   147  	qv := u.Query()
   148  	if qv.Get("discport") != "" {
   149  		udpPort, err = strconv.ParseUint(qv.Get("discport"), 10, 16)
   150  		if err != nil {
   151  			return nil, errors.New("invalid discport in query")
   152  		}
   153  	}
   154  	return NewV4(id, ip, int(tcpPort), int(udpPort)), nil
   155  }
   156  
   157  // parsePubkey parses a hex-encoded secp256k1 public key.
   158  func parsePubkey(in string) (*ecdsa.PublicKey, error) {
   159  	b, err := hex.DecodeString(in)
   160  	if err != nil {
   161  		return nil, err
   162  	} else if len(b) != 64 {
   163  		return nil, fmt.Errorf("wrong length, want %d hex chars", 128)
   164  	}
   165  	b = append([]byte{0x4}, b...)
   166  	return crypto.UnmarshalPubkey(b)
   167  }
   168  
   169  func (n *Node) URLv4() string {
   170  	var (
   171  		scheme enr.ID
   172  		nodeid string
   173  		key    ecdsa.PublicKey
   174  	)
   175  	n.Load(&scheme)
   176  	n.Load((*Secp256k1)(&key))
   177  	switch {
   178  	case scheme == "v4" || key != ecdsa.PublicKey{}:
   179  		nodeid = fmt.Sprintf("%x", crypto.FromECDSAPub(&key)[1:])
   180  	default:
   181  		nodeid = fmt.Sprintf("%s.%x", scheme, n.id[:])
   182  	}
   183  	u := url.URL{Scheme: "enode"}
   184  	if n.Incomplete() {
   185  		u.Host = nodeid
   186  	} else {
   187  		addr := net.TCPAddr{IP: n.IP(), Port: n.TCP()}
   188  		u.User = url.User(nodeid)
   189  		u.Host = addr.String()
   190  		if n.UDP() != n.TCP() {
   191  			u.RawQuery = "discport=" + strconv.Itoa(n.UDP())
   192  		}
   193  	}
   194  	return u.String()
   195  }
   196  
   197  // PubkeyToIDV4 derives the v4 node address from the given public key.
   198  func PubkeyToIDV4(key *ecdsa.PublicKey) ID {
   199  	e := make([]byte, 64)
   200  	math.ReadBits(key.X, e[:len(e)/2])
   201  	math.ReadBits(key.Y, e[len(e)/2:])
   202  	return ID(crypto.Keccak256Hash(e))
   203  }