gitee.com/liu-zhao234568/cntest@v1.0.0/p2p/discover/node.go (about) 1 // Copyright 2015 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 discover 18 19 import ( 20 "crypto/ecdsa" 21 "crypto/elliptic" 22 "errors" 23 "math/big" 24 "net" 25 "time" 26 27 "gitee.com/liu-zhao234568/cntest/common/math" 28 "gitee.com/liu-zhao234568/cntest/crypto" 29 "gitee.com/liu-zhao234568/cntest/p2p/enode" 30 ) 31 32 // node represents a host on the network. 33 // The fields of Node may not be modified. 34 type node struct { 35 enode.Node 36 addedAt time.Time // time when the node was added to the table 37 livenessChecks uint // how often liveness was checked 38 } 39 40 type encPubkey [64]byte 41 42 func encodePubkey(key *ecdsa.PublicKey) encPubkey { 43 var e encPubkey 44 math.ReadBits(key.X, e[:len(e)/2]) 45 math.ReadBits(key.Y, e[len(e)/2:]) 46 return e 47 } 48 49 func decodePubkey(curve elliptic.Curve, e []byte) (*ecdsa.PublicKey, error) { 50 if len(e) != len(encPubkey{}) { 51 return nil, errors.New("wrong size public key data") 52 } 53 p := &ecdsa.PublicKey{Curve: curve, X: new(big.Int), Y: new(big.Int)} 54 half := len(e) / 2 55 p.X.SetBytes(e[:half]) 56 p.Y.SetBytes(e[half:]) 57 if !p.Curve.IsOnCurve(p.X, p.Y) { 58 return nil, errors.New("invalid curve point") 59 } 60 return p, nil 61 } 62 63 func (e encPubkey) id() enode.ID { 64 return enode.ID(crypto.Keccak256Hash(e[:])) 65 } 66 67 func wrapNode(n *enode.Node) *node { 68 return &node{Node: *n} 69 } 70 71 func wrapNodes(ns []*enode.Node) []*node { 72 result := make([]*node, len(ns)) 73 for i, n := range ns { 74 result[i] = wrapNode(n) 75 } 76 return result 77 } 78 79 func unwrapNode(n *node) *enode.Node { 80 return &n.Node 81 } 82 83 func unwrapNodes(ns []*node) []*enode.Node { 84 result := make([]*enode.Node, len(ns)) 85 for i, n := range ns { 86 result[i] = unwrapNode(n) 87 } 88 return result 89 } 90 91 func (n *node) addr() *net.UDPAddr { 92 return &net.UDPAddr{IP: n.IP(), Port: n.UDP()} 93 } 94 95 func (n *node) String() string { 96 return n.Node.String() 97 }