github.com/status-im/status-go@v1.1.0/server/pairing/peers/payload.go (about)

     1  package peers
     2  
     3  import (
     4  	"crypto/ecdsa"
     5  	"crypto/rand"
     6  	"crypto/sha256"
     7  	"encoding/json"
     8  
     9  	udpp2p "github.com/schollz/peerdiscovery"
    10  
    11  	"github.com/status-im/status-go/protocol/protobuf"
    12  )
    13  
    14  type LocalPairingPeerHello struct {
    15  	protobuf.LocalPairingPeerHello
    16  	Discovered udpp2p.Discovered
    17  }
    18  
    19  func NewLocalPairingPeerHello(id []byte, name, deviceType string, k *ecdsa.PrivateKey) (*LocalPairingPeerHello, error) {
    20  	h := new(LocalPairingPeerHello)
    21  
    22  	h.PeerId = id
    23  	h.DeviceName = name
    24  	h.DeviceType = deviceType
    25  
    26  	err := h.sign(k)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  
    31  	return h, nil
    32  }
    33  
    34  func (h *LocalPairingPeerHello) MarshalJSON() ([]byte, error) {
    35  	alias := struct {
    36  		PeerID     []byte
    37  		DeviceName string
    38  		DeviceType string
    39  		Address    string
    40  	}{
    41  		PeerID:     h.PeerId,
    42  		DeviceName: h.DeviceName,
    43  		DeviceType: h.DeviceType,
    44  		Address:    h.Discovered.Address,
    45  	}
    46  
    47  	return json.Marshal(alias)
    48  }
    49  
    50  func (h *LocalPairingPeerHello) hash() []byte {
    51  	dHash := sha256.Sum256(append(h.PeerId, []byte(h.DeviceName+h.DeviceType)...))
    52  	return dHash[:]
    53  }
    54  
    55  func (h *LocalPairingPeerHello) sign(k *ecdsa.PrivateKey) error {
    56  	s, err := ecdsa.SignASN1(rand.Reader, k, h.hash())
    57  	if err != nil {
    58  		return err
    59  	}
    60  
    61  	h.Signature = s
    62  	return nil
    63  }
    64  
    65  func (h *LocalPairingPeerHello) verify(k *ecdsa.PublicKey) bool {
    66  	return ecdsa.VerifyASN1(k, h.hash(), h.Signature)
    67  }