2023-04-08 22:38:04 +00:00
|
|
|
package peers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ecdsa"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/sha256"
|
2023-04-12 13:36:38 +00:00
|
|
|
"encoding/json"
|
2023-04-08 22:38:04 +00:00
|
|
|
|
|
|
|
udpp2p "github.com/schollz/peerdiscovery"
|
|
|
|
|
|
|
|
"github.com/status-im/status-go/protocol/protobuf"
|
2023-04-17 08:54:03 +00:00
|
|
|
"github.com/status-im/status-go/server/pairing/versioning"
|
2023-04-08 22:38:04 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type LocalPairingPeerHello struct {
|
|
|
|
protobuf.LocalPairingPeerHello
|
|
|
|
Discovered udpp2p.Discovered
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewLocalPairingPeerHello(id []byte, name, deviceType string, k *ecdsa.PrivateKey) (*LocalPairingPeerHello, error) {
|
|
|
|
h := new(LocalPairingPeerHello)
|
|
|
|
|
2023-04-17 08:54:03 +00:00
|
|
|
h.PairingVersion = int32(versioning.LatestLocalPairingVer)
|
2023-04-08 22:38:04 +00:00
|
|
|
h.PeerId = id
|
|
|
|
h.DeviceName = name
|
|
|
|
h.DeviceType = deviceType
|
|
|
|
|
|
|
|
err := h.sign(k)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return h, nil
|
|
|
|
}
|
|
|
|
|
2023-04-12 13:36:38 +00:00
|
|
|
func (h *LocalPairingPeerHello) MarshalJSON() ([]byte, error) {
|
|
|
|
alias := struct {
|
2023-04-17 08:54:03 +00:00
|
|
|
PairingVersion int32
|
|
|
|
PeerID []byte
|
|
|
|
DeviceName string
|
|
|
|
DeviceType string
|
|
|
|
Address string
|
2023-04-12 13:36:38 +00:00
|
|
|
}{
|
2023-04-17 08:54:03 +00:00
|
|
|
PairingVersion: h.PairingVersion,
|
|
|
|
PeerID: h.PeerId,
|
|
|
|
DeviceName: h.DeviceName,
|
|
|
|
DeviceType: h.DeviceType,
|
|
|
|
Address: h.Discovered.Address,
|
2023-04-12 13:36:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return json.Marshal(alias)
|
|
|
|
}
|
|
|
|
|
2023-04-08 22:38:04 +00:00
|
|
|
func (h *LocalPairingPeerHello) hash() []byte {
|
|
|
|
dHash := sha256.Sum256(append(h.PeerId, []byte(h.DeviceName+h.DeviceType)...))
|
|
|
|
return dHash[:]
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *LocalPairingPeerHello) sign(k *ecdsa.PrivateKey) error {
|
|
|
|
s, err := ecdsa.SignASN1(rand.Reader, k, h.hash())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
h.Signature = s
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *LocalPairingPeerHello) verify(k *ecdsa.PublicKey) bool {
|
|
|
|
return ecdsa.VerifyASN1(k, h.hash(), h.Signature)
|
|
|
|
}
|