github.com/nitinawathare/ethereumassignment3@v0.0.0-20211021213010-f07344c2b868/go-ethereum/swarm/network/network.go (about) 1 package network 2 3 import ( 4 "crypto/ecdsa" 5 "fmt" 6 "net" 7 8 "github.com/ethereum/go-ethereum/crypto" 9 "github.com/ethereum/go-ethereum/p2p/enode" 10 "github.com/ethereum/go-ethereum/p2p/enr" 11 ) 12 13 // BzzAddr implements the PeerAddr interface 14 type BzzAddr struct { 15 OAddr []byte 16 UAddr []byte 17 } 18 19 // Address implements OverlayPeer interface to be used in Overlay. 20 func (a *BzzAddr) Address() []byte { 21 return a.OAddr 22 } 23 24 // Over returns the overlay address. 25 func (a *BzzAddr) Over() []byte { 26 return a.OAddr 27 } 28 29 // Under returns the underlay address. 30 func (a *BzzAddr) Under() []byte { 31 return a.UAddr 32 } 33 34 // ID returns the node identifier in the underlay. 35 func (a *BzzAddr) ID() enode.ID { 36 n, err := enode.ParseV4(string(a.UAddr)) 37 if err != nil { 38 return enode.ID{} 39 } 40 return n.ID() 41 } 42 43 // Update updates the underlay address of a peer record 44 func (a *BzzAddr) Update(na *BzzAddr) *BzzAddr { 45 return &BzzAddr{a.OAddr, na.UAddr} 46 } 47 48 // String pretty prints the address 49 func (a *BzzAddr) String() string { 50 return fmt.Sprintf("%x <%s>", a.OAddr, a.UAddr) 51 } 52 53 // RandomAddr is a utility method generating an address from a public key 54 func RandomAddr() *BzzAddr { 55 key, err := crypto.GenerateKey() 56 if err != nil { 57 panic("unable to generate key") 58 } 59 node := enode.NewV4(&key.PublicKey, net.IP{127, 0, 0, 1}, 30303, 30303) 60 return NewAddr(node) 61 } 62 63 // NewAddr constucts a BzzAddr from a node record. 64 func NewAddr(node *enode.Node) *BzzAddr { 65 return &BzzAddr{OAddr: node.ID().Bytes(), UAddr: []byte(node.String())} 66 } 67 68 func PrivateKeyToBzzKey(prvKey *ecdsa.PrivateKey) []byte { 69 pubkeyBytes := crypto.FromECDSAPub(&prvKey.PublicKey) 70 return crypto.Keccak256Hash(pubkeyBytes).Bytes() 71 } 72 73 type EnodeParams struct { 74 PrivateKey *ecdsa.PrivateKey 75 EnodeKey *ecdsa.PrivateKey 76 Lightnode bool 77 Bootnode bool 78 } 79 80 func NewEnodeRecord(params *EnodeParams) (*enr.Record, error) { 81 82 if params.PrivateKey == nil { 83 return nil, fmt.Errorf("all param private keys must be defined") 84 } 85 86 bzzkeybytes := PrivateKeyToBzzKey(params.PrivateKey) 87 88 var record enr.Record 89 record.Set(NewENRAddrEntry(bzzkeybytes)) 90 record.Set(ENRLightNodeEntry(params.Lightnode)) 91 record.Set(ENRBootNodeEntry(params.Bootnode)) 92 return &record, nil 93 } 94 95 func NewEnode(params *EnodeParams) (*enode.Node, error) { 96 record, err := NewEnodeRecord(params) 97 if err != nil { 98 return nil, err 99 } 100 err = enode.SignV4(record, params.EnodeKey) 101 if err != nil { 102 return nil, fmt.Errorf("ENR create fail: %v", err) 103 } 104 return enode.New(enode.V4ID{}, record) 105 }