2017-11-03 15:29:49 -05:00
|
|
|
// Copyright 2016 The go-ethereum Authors
|
|
|
|
// This file is part of the go-ethereum library.
|
|
|
|
//
|
|
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU Lesser General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Lesser General Public License
|
|
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
package whisperv6
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"crypto/ecdsa"
|
|
|
|
"crypto/sha256"
|
|
|
|
"fmt"
|
2017-12-21 08:17:27 -06:00
|
|
|
"math"
|
2017-11-03 15:29:49 -05:00
|
|
|
"runtime"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2018-07-16 02:54:19 -05:00
|
|
|
mapset "github.com/deckarep/golang-set"
|
2017-11-03 15:29:49 -05:00
|
|
|
"github.com/ethereum/go-ethereum/common"
|
|
|
|
"github.com/ethereum/go-ethereum/crypto"
|
|
|
|
"github.com/ethereum/go-ethereum/log"
|
|
|
|
"github.com/ethereum/go-ethereum/p2p"
|
2017-12-21 08:17:27 -06:00
|
|
|
"github.com/ethereum/go-ethereum/rlp"
|
2017-11-03 15:29:49 -05:00
|
|
|
"github.com/ethereum/go-ethereum/rpc"
|
|
|
|
"github.com/syndtr/goleveldb/leveldb/errors"
|
|
|
|
"golang.org/x/crypto/pbkdf2"
|
|
|
|
"golang.org/x/sync/syncmap"
|
|
|
|
)
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
// Statistics holds several message-related counter for analytics
|
|
|
|
// purposes.
|
2017-11-03 15:29:49 -05:00
|
|
|
type Statistics struct {
|
|
|
|
messagesCleared int
|
|
|
|
memoryCleared int
|
|
|
|
memoryUsed int
|
|
|
|
cycles int
|
|
|
|
totalMessagesCleared int
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
2018-09-05 03:57:45 -05:00
|
|
|
maxMsgSizeIdx = iota // Maximal message length allowed by the whisper node
|
|
|
|
overflowIdx // Indicator of message queue overflow
|
|
|
|
minPowIdx // Minimal PoW required by the whisper node
|
|
|
|
minPowToleranceIdx // Minimal PoW tolerated by the whisper node for a limited time
|
|
|
|
bloomFilterIdx // Bloom filter for topics of interest for this node
|
|
|
|
bloomFilterToleranceIdx // Bloom filter tolerated by the whisper node for a limited time
|
|
|
|
lightClientModeIdx // Light client mode. (does not forward any messages)
|
|
|
|
restrictConnectionBetweenLightClientsIdx // Restrict connection between two light clients
|
2017-11-03 15:29:49 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// Whisper represents a dark communication interface through the Ethereum
|
|
|
|
// network, using its very own P2P communication layer.
|
|
|
|
type Whisper struct {
|
|
|
|
protocol p2p.Protocol // Protocol description and parameters
|
|
|
|
filters *Filters // Message filters installed with Subscribe function
|
|
|
|
|
|
|
|
privateKeys map[string]*ecdsa.PrivateKey // Private key storage
|
|
|
|
symKeys map[string][]byte // Symmetric key storage
|
|
|
|
keyMu sync.RWMutex // Mutex associated with key storages
|
|
|
|
|
|
|
|
poolMu sync.RWMutex // Mutex to sync the message and expiration pools
|
|
|
|
envelopes map[common.Hash]*Envelope // Pool of envelopes currently tracked by this node
|
2018-07-16 02:54:19 -05:00
|
|
|
expirations map[uint32]mapset.Set // Message expiration pool
|
2017-11-03 15:29:49 -05:00
|
|
|
|
|
|
|
peerMu sync.RWMutex // Mutex to sync the active peer set
|
|
|
|
peers map[*Peer]struct{} // Set of currently active peers
|
|
|
|
|
|
|
|
messageQueue chan *Envelope // Message queue for normal whisper messages
|
|
|
|
p2pMsgQueue chan *Envelope // Message queue for peer-to-peer messages (not to be forwarded any further)
|
|
|
|
quit chan struct{} // Channel used for graceful exit
|
|
|
|
|
|
|
|
settings syncmap.Map // holds configuration settings that can be dynamically changed
|
|
|
|
|
2018-01-12 05:11:22 -06:00
|
|
|
syncAllowance int // maximum time in seconds allowed to process the whisper-related messages
|
2017-12-21 08:17:27 -06:00
|
|
|
|
2017-11-03 15:29:49 -05:00
|
|
|
statsMu sync.Mutex // guard stats
|
|
|
|
stats Statistics // Statistics of whisper node
|
|
|
|
|
|
|
|
mailServer MailServer // MailServer interface
|
2020-04-01 04:35:26 -05:00
|
|
|
|
|
|
|
wg sync.WaitGroup
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// New creates a Whisper client ready to communicate through the Ethereum P2P network.
|
|
|
|
func New(cfg *Config) *Whisper {
|
|
|
|
if cfg == nil {
|
|
|
|
cfg = &DefaultConfig
|
|
|
|
}
|
|
|
|
|
|
|
|
whisper := &Whisper{
|
2018-01-12 05:11:22 -06:00
|
|
|
privateKeys: make(map[string]*ecdsa.PrivateKey),
|
|
|
|
symKeys: make(map[string][]byte),
|
|
|
|
envelopes: make(map[common.Hash]*Envelope),
|
2018-07-16 02:54:19 -05:00
|
|
|
expirations: make(map[uint32]mapset.Set),
|
2018-01-12 05:11:22 -06:00
|
|
|
peers: make(map[*Peer]struct{}),
|
|
|
|
messageQueue: make(chan *Envelope, messageQueueLimit),
|
|
|
|
p2pMsgQueue: make(chan *Envelope, messageQueueLimit),
|
|
|
|
quit: make(chan struct{}),
|
|
|
|
syncAllowance: DefaultSyncAllowance,
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
whisper.filters = NewFilters(whisper)
|
|
|
|
|
|
|
|
whisper.settings.Store(minPowIdx, cfg.MinimumAcceptedPOW)
|
|
|
|
whisper.settings.Store(maxMsgSizeIdx, cfg.MaxMessageSize)
|
|
|
|
whisper.settings.Store(overflowIdx, false)
|
2018-09-05 03:57:45 -05:00
|
|
|
whisper.settings.Store(restrictConnectionBetweenLightClientsIdx, cfg.RestrictConnectionBetweenLightClients)
|
2017-11-03 15:29:49 -05:00
|
|
|
|
|
|
|
// p2p whisper sub protocol handler
|
|
|
|
whisper.protocol = p2p.Protocol{
|
|
|
|
Name: ProtocolName,
|
|
|
|
Version: uint(ProtocolVersion),
|
|
|
|
Length: NumberOfMessageCodes,
|
|
|
|
Run: whisper.HandlePeer,
|
|
|
|
NodeInfo: func() interface{} {
|
|
|
|
return map[string]interface{}{
|
|
|
|
"version": ProtocolVersionStr,
|
|
|
|
"maxMessageSize": whisper.MaxMessageSize(),
|
|
|
|
"minimumPoW": whisper.MinPow(),
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
return whisper
|
|
|
|
}
|
|
|
|
|
2018-01-12 05:11:22 -06:00
|
|
|
// MinPow returns the PoW value required by this node.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) MinPow() float64 {
|
|
|
|
val, exist := whisper.settings.Load(minPowIdx)
|
2018-01-12 05:11:22 -06:00
|
|
|
if !exist || val == nil {
|
|
|
|
return DefaultMinimumPoW
|
|
|
|
}
|
|
|
|
v, ok := val.(float64)
|
|
|
|
if !ok {
|
|
|
|
log.Error("Error loading minPowIdx, using default")
|
|
|
|
return DefaultMinimumPoW
|
|
|
|
}
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
|
|
|
|
// MinPowTolerance returns the value of minimum PoW which is tolerated for a limited
|
|
|
|
// time after PoW was changed. If sufficient time have elapsed or no change of PoW
|
|
|
|
// have ever occurred, the return value will be the same as return value of MinPow().
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) MinPowTolerance() float64 {
|
|
|
|
val, exist := whisper.settings.Load(minPowToleranceIdx)
|
2018-01-12 05:11:22 -06:00
|
|
|
if !exist || val == nil {
|
|
|
|
return DefaultMinimumPoW
|
|
|
|
}
|
2017-11-03 15:29:49 -05:00
|
|
|
return val.(float64)
|
|
|
|
}
|
|
|
|
|
2018-01-12 05:11:22 -06:00
|
|
|
// BloomFilter returns the aggregated bloom filter for all the topics of interest.
|
|
|
|
// The nodes are required to send only messages that match the advertised bloom filter.
|
|
|
|
// If a message does not match the bloom, it will tantamount to spam, and the peer will
|
|
|
|
// be disconnected.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) BloomFilter() []byte {
|
|
|
|
val, exist := whisper.settings.Load(bloomFilterIdx)
|
2018-01-12 05:11:22 -06:00
|
|
|
if !exist || val == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return val.([]byte)
|
|
|
|
}
|
|
|
|
|
|
|
|
// BloomFilterTolerance returns the bloom filter which is tolerated for a limited
|
|
|
|
// time after new bloom was advertised to the peers. If sufficient time have elapsed
|
|
|
|
// or no change of bloom filter have ever occurred, the return value will be the same
|
|
|
|
// as return value of BloomFilter().
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) BloomFilterTolerance() []byte {
|
|
|
|
val, exist := whisper.settings.Load(bloomFilterToleranceIdx)
|
2018-01-12 05:11:22 -06:00
|
|
|
if !exist || val == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return val.([]byte)
|
|
|
|
}
|
|
|
|
|
2017-11-03 15:29:49 -05:00
|
|
|
// MaxMessageSize returns the maximum accepted message size.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) MaxMessageSize() uint32 {
|
|
|
|
val, _ := whisper.settings.Load(maxMsgSizeIdx)
|
2017-11-03 15:29:49 -05:00
|
|
|
return val.(uint32)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Overflow returns an indication if the message queue is full.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) Overflow() bool {
|
|
|
|
val, _ := whisper.settings.Load(overflowIdx)
|
2017-11-03 15:29:49 -05:00
|
|
|
return val.(bool)
|
|
|
|
}
|
|
|
|
|
|
|
|
// APIs returns the RPC descriptors the Whisper implementation offers
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) APIs() []rpc.API {
|
2017-11-03 15:29:49 -05:00
|
|
|
return []rpc.API{
|
|
|
|
{
|
|
|
|
Namespace: ProtocolName,
|
|
|
|
Version: ProtocolVersionStr,
|
2018-01-26 05:45:10 -06:00
|
|
|
Service: NewPublicWhisperAPI(whisper),
|
2017-11-03 15:29:49 -05:00
|
|
|
Public: true,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// RegisterServer registers MailServer interface.
|
|
|
|
// MailServer will process all the incoming messages with p2pRequestCode.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) RegisterServer(server MailServer) {
|
|
|
|
whisper.mailServer = server
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Protocols returns the whisper sub-protocols ran by this particular client.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) Protocols() []p2p.Protocol {
|
|
|
|
return []p2p.Protocol{whisper.protocol}
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Version returns the whisper sub-protocols version number.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) Version() uint {
|
|
|
|
return whisper.protocol.Version
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetMaxMessageSize sets the maximal message size allowed by this node
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) SetMaxMessageSize(size uint32) error {
|
2017-11-03 15:29:49 -05:00
|
|
|
if size > MaxMessageSize {
|
|
|
|
return fmt.Errorf("message size too large [%d>%d]", size, MaxMessageSize)
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.settings.Store(maxMsgSizeIdx, size)
|
2017-11-03 15:29:49 -05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-01-12 05:11:22 -06:00
|
|
|
// SetBloomFilter sets the new bloom filter
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) SetBloomFilter(bloom []byte) error {
|
2018-03-01 09:04:09 -06:00
|
|
|
if len(bloom) != BloomFilterSize {
|
2018-01-12 05:11:22 -06:00
|
|
|
return fmt.Errorf("invalid bloom filter size: %d", len(bloom))
|
|
|
|
}
|
|
|
|
|
2018-03-01 09:04:09 -06:00
|
|
|
b := make([]byte, BloomFilterSize)
|
2018-01-12 05:11:22 -06:00
|
|
|
copy(b, bloom)
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.settings.Store(bloomFilterIdx, b)
|
|
|
|
whisper.notifyPeersAboutBloomFilterChange(b)
|
2018-01-12 05:11:22 -06:00
|
|
|
|
2020-04-01 04:35:26 -05:00
|
|
|
whisper.wg.Add(1)
|
2018-01-12 05:11:22 -06:00
|
|
|
go func() {
|
|
|
|
// allow some time before all the peers have processed the notification
|
2020-04-01 04:35:26 -05:00
|
|
|
defer whisper.wg.Done()
|
2018-01-26 05:45:10 -06:00
|
|
|
time.Sleep(time.Duration(whisper.syncAllowance) * time.Second)
|
|
|
|
whisper.settings.Store(bloomFilterToleranceIdx, b)
|
2018-01-12 05:11:22 -06:00
|
|
|
}()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-11-03 15:29:49 -05:00
|
|
|
// SetMinimumPoW sets the minimal PoW required by this node
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) SetMinimumPoW(val float64) error {
|
2017-12-21 08:17:27 -06:00
|
|
|
if val < 0.0 {
|
2017-11-03 15:29:49 -05:00
|
|
|
return fmt.Errorf("invalid PoW: %f", val)
|
|
|
|
}
|
2017-12-21 08:17:27 -06:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.settings.Store(minPowIdx, val)
|
|
|
|
whisper.notifyPeersAboutPowRequirementChange(val)
|
2017-12-21 08:17:27 -06:00
|
|
|
|
2020-04-01 04:35:26 -05:00
|
|
|
whisper.wg.Add(1)
|
2017-12-21 08:17:27 -06:00
|
|
|
go func() {
|
2020-04-01 04:35:26 -05:00
|
|
|
defer whisper.wg.Done()
|
2017-12-21 08:17:27 -06:00
|
|
|
// allow some time before all the peers have processed the notification
|
2018-01-26 05:45:10 -06:00
|
|
|
time.Sleep(time.Duration(whisper.syncAllowance) * time.Second)
|
|
|
|
whisper.settings.Store(minPowToleranceIdx, val)
|
2017-12-21 08:17:27 -06:00
|
|
|
}()
|
|
|
|
|
2017-11-03 15:29:49 -05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
// SetMinimumPowTest sets the minimal PoW in test environment
|
|
|
|
func (whisper *Whisper) SetMinimumPowTest(val float64) {
|
|
|
|
whisper.settings.Store(minPowIdx, val)
|
|
|
|
whisper.notifyPeersAboutPowRequirementChange(val)
|
|
|
|
whisper.settings.Store(minPowToleranceIdx, val)
|
2017-12-21 08:17:27 -06:00
|
|
|
}
|
|
|
|
|
2018-09-05 03:57:45 -05:00
|
|
|
//SetLightClientMode makes node light client (does not forward any messages)
|
|
|
|
func (whisper *Whisper) SetLightClientMode(v bool) {
|
|
|
|
whisper.settings.Store(lightClientModeIdx, v)
|
|
|
|
}
|
|
|
|
|
|
|
|
//LightClientMode indicates is this node is light client (does not forward any messages)
|
|
|
|
func (whisper *Whisper) LightClientMode() bool {
|
|
|
|
val, exist := whisper.settings.Load(lightClientModeIdx)
|
|
|
|
if !exist || val == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
v, ok := val.(bool)
|
|
|
|
return v && ok
|
|
|
|
}
|
|
|
|
|
|
|
|
//LightClientModeConnectionRestricted indicates that connection to light client in light client mode not allowed
|
|
|
|
func (whisper *Whisper) LightClientModeConnectionRestricted() bool {
|
|
|
|
val, exist := whisper.settings.Load(restrictConnectionBetweenLightClientsIdx)
|
|
|
|
if !exist || val == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
v, ok := val.(bool)
|
|
|
|
return v && ok
|
|
|
|
}
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) notifyPeersAboutPowRequirementChange(pow float64) {
|
|
|
|
arr := whisper.getPeers()
|
2017-12-21 08:17:27 -06:00
|
|
|
for _, p := range arr {
|
|
|
|
err := p.notifyAboutPowRequirementChange(pow)
|
|
|
|
if err != nil {
|
|
|
|
// allow one retry
|
|
|
|
err = p.notifyAboutPowRequirementChange(pow)
|
|
|
|
}
|
|
|
|
if err != nil {
|
2018-01-12 05:11:22 -06:00
|
|
|
log.Warn("failed to notify peer about new pow requirement", "peer", p.ID(), "error", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) notifyPeersAboutBloomFilterChange(bloom []byte) {
|
|
|
|
arr := whisper.getPeers()
|
2018-01-12 05:11:22 -06:00
|
|
|
for _, p := range arr {
|
|
|
|
err := p.notifyAboutBloomFilterChange(bloom)
|
|
|
|
if err != nil {
|
|
|
|
// allow one retry
|
|
|
|
err = p.notifyAboutBloomFilterChange(bloom)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
log.Warn("failed to notify peer about new bloom filter", "peer", p.ID(), "error", err)
|
2017-12-21 08:17:27 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) getPeers() []*Peer {
|
|
|
|
arr := make([]*Peer, len(whisper.peers))
|
2018-01-12 05:11:22 -06:00
|
|
|
i := 0
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.peerMu.Lock()
|
|
|
|
for p := range whisper.peers {
|
2018-01-12 05:11:22 -06:00
|
|
|
arr[i] = p
|
|
|
|
i++
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.peerMu.Unlock()
|
2018-01-12 05:11:22 -06:00
|
|
|
return arr
|
|
|
|
}
|
|
|
|
|
2017-11-03 15:29:49 -05:00
|
|
|
// getPeer retrieves peer by ID
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) getPeer(peerID []byte) (*Peer, error) {
|
|
|
|
whisper.peerMu.Lock()
|
|
|
|
defer whisper.peerMu.Unlock()
|
|
|
|
for p := range whisper.peers {
|
2017-11-03 15:29:49 -05:00
|
|
|
id := p.peer.ID()
|
|
|
|
if bytes.Equal(peerID, id[:]) {
|
|
|
|
return p, nil
|
|
|
|
}
|
|
|
|
}
|
2019-11-14 03:09:16 -06:00
|
|
|
return nil, fmt.Errorf("could not find peer with ID: %x", peerID)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// AllowP2PMessagesFromPeer marks specific peer trusted,
|
|
|
|
// which will allow it to send historic (expired) messages.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) AllowP2PMessagesFromPeer(peerID []byte) error {
|
|
|
|
p, err := whisper.getPeer(peerID)
|
2017-11-03 15:29:49 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
p.trusted = true
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RequestHistoricMessages sends a message with p2pRequestCode to a specific peer,
|
|
|
|
// which is known to implement MailServer interface, and is supposed to process this
|
|
|
|
// request and respond with a number of peer-to-peer messages (possibly expired),
|
|
|
|
// which are not supposed to be forwarded any further.
|
|
|
|
// The whisper protocol is agnostic of the format and contents of envelope.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) RequestHistoricMessages(peerID []byte, envelope *Envelope) error {
|
|
|
|
p, err := whisper.getPeer(peerID)
|
2017-11-03 15:29:49 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
p.trusted = true
|
|
|
|
return p2p.Send(p.ws, p2pRequestCode, envelope)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SendP2PMessage sends a peer-to-peer message to a specific peer.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) SendP2PMessage(peerID []byte, envelope *Envelope) error {
|
|
|
|
p, err := whisper.getPeer(peerID)
|
2017-11-03 15:29:49 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
return whisper.SendP2PDirect(p, envelope)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// SendP2PDirect sends a peer-to-peer message to a specific peer.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) SendP2PDirect(peer *Peer, envelope *Envelope) error {
|
2017-12-21 08:17:27 -06:00
|
|
|
return p2p.Send(peer.ws, p2pMessageCode, envelope)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewKeyPair generates a new cryptographic identity for the client, and injects
|
|
|
|
// it into the known identities for message decryption. Returns ID of the new key pair.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) NewKeyPair() (string, error) {
|
2017-11-03 15:29:49 -05:00
|
|
|
key, err := crypto.GenerateKey()
|
|
|
|
if err != nil || !validatePrivateKey(key) {
|
|
|
|
key, err = crypto.GenerateKey() // retry once
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if !validatePrivateKey(key) {
|
|
|
|
return "", fmt.Errorf("failed to generate valid key")
|
|
|
|
}
|
|
|
|
|
|
|
|
id, err := GenerateRandomID()
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate ID: %s", err)
|
|
|
|
}
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.keyMu.Lock()
|
|
|
|
defer whisper.keyMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
if whisper.privateKeys[id] != nil {
|
2017-11-03 15:29:49 -05:00
|
|
|
return "", fmt.Errorf("failed to generate unique ID")
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.privateKeys[id] = key
|
2017-11-03 15:29:49 -05:00
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteKeyPair deletes the specified key if it exists.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) DeleteKeyPair(key string) bool {
|
|
|
|
whisper.keyMu.Lock()
|
|
|
|
defer whisper.keyMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
if whisper.privateKeys[key] != nil {
|
|
|
|
delete(whisper.privateKeys, key)
|
2017-11-03 15:29:49 -05:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddKeyPair imports a asymmetric private key and returns it identifier.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) AddKeyPair(key *ecdsa.PrivateKey) (string, error) {
|
2017-11-03 15:29:49 -05:00
|
|
|
id, err := GenerateRandomID()
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate ID: %s", err)
|
|
|
|
}
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.keyMu.Lock()
|
|
|
|
whisper.privateKeys[id] = key
|
|
|
|
whisper.keyMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
2018-08-27 03:49:29 -05:00
|
|
|
// HasKeyPair checks if the whisper node is configured with the private key
|
2017-11-03 15:29:49 -05:00
|
|
|
// of the specified public pair.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) HasKeyPair(id string) bool {
|
|
|
|
whisper.keyMu.RLock()
|
|
|
|
defer whisper.keyMu.RUnlock()
|
|
|
|
return whisper.privateKeys[id] != nil
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetPrivateKey retrieves the private key of the specified identity.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) GetPrivateKey(id string) (*ecdsa.PrivateKey, error) {
|
|
|
|
whisper.keyMu.RLock()
|
|
|
|
defer whisper.keyMu.RUnlock()
|
|
|
|
key := whisper.privateKeys[id]
|
2017-11-03 15:29:49 -05:00
|
|
|
if key == nil {
|
|
|
|
return nil, fmt.Errorf("invalid id")
|
|
|
|
}
|
|
|
|
return key, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// GenerateSymKey generates a random symmetric key and stores it under id,
|
|
|
|
// which is then returned. Will be used in the future for session key exchange.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) GenerateSymKey() (string, error) {
|
2018-01-30 02:55:08 -06:00
|
|
|
key, err := generateSecureRandomData(aesKeyLength)
|
2017-11-03 15:29:49 -05:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
2018-01-30 02:55:08 -06:00
|
|
|
} else if !validateDataIntegrity(key, aesKeyLength) {
|
2017-11-03 15:29:49 -05:00
|
|
|
return "", fmt.Errorf("error in GenerateSymKey: crypto/rand failed to generate random data")
|
|
|
|
}
|
|
|
|
|
|
|
|
id, err := GenerateRandomID()
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate ID: %s", err)
|
|
|
|
}
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.keyMu.Lock()
|
|
|
|
defer whisper.keyMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
if whisper.symKeys[id] != nil {
|
2017-11-03 15:29:49 -05:00
|
|
|
return "", fmt.Errorf("failed to generate unique ID")
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.symKeys[id] = key
|
2017-11-03 15:29:49 -05:00
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddSymKeyDirect stores the key, and returns its id.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) AddSymKeyDirect(key []byte) (string, error) {
|
2017-11-03 15:29:49 -05:00
|
|
|
if len(key) != aesKeyLength {
|
|
|
|
return "", fmt.Errorf("wrong key size: %d", len(key))
|
|
|
|
}
|
|
|
|
|
|
|
|
id, err := GenerateRandomID()
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate ID: %s", err)
|
|
|
|
}
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.keyMu.Lock()
|
|
|
|
defer whisper.keyMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
if whisper.symKeys[id] != nil {
|
2017-11-03 15:29:49 -05:00
|
|
|
return "", fmt.Errorf("failed to generate unique ID")
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.symKeys[id] = key
|
2017-11-03 15:29:49 -05:00
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddSymKeyFromPassword generates the key from password, stores it, and returns its id.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) AddSymKeyFromPassword(password string) (string, error) {
|
2017-11-03 15:29:49 -05:00
|
|
|
id, err := GenerateRandomID()
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate ID: %s", err)
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
if whisper.HasSymKey(id) {
|
2017-11-03 15:29:49 -05:00
|
|
|
return "", fmt.Errorf("failed to generate unique ID")
|
|
|
|
}
|
|
|
|
|
2017-12-08 09:08:56 -06:00
|
|
|
// kdf should run no less than 0.1 seconds on an average computer,
|
|
|
|
// because it's an once in a session experience
|
|
|
|
derived := pbkdf2.Key([]byte(password), nil, 65356, aesKeyLength, sha256.New)
|
2017-11-03 15:29:49 -05:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.keyMu.Lock()
|
|
|
|
defer whisper.keyMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
|
|
|
// double check is necessary, because deriveKeyMaterial() is very slow
|
2018-01-26 05:45:10 -06:00
|
|
|
if whisper.symKeys[id] != nil {
|
2017-11-03 15:29:49 -05:00
|
|
|
return "", fmt.Errorf("critical error: failed to generate unique ID")
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.symKeys[id] = derived
|
2017-11-03 15:29:49 -05:00
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// HasSymKey returns true if there is a key associated with the given id.
|
|
|
|
// Otherwise returns false.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) HasSymKey(id string) bool {
|
|
|
|
whisper.keyMu.RLock()
|
|
|
|
defer whisper.keyMu.RUnlock()
|
|
|
|
return whisper.symKeys[id] != nil
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteSymKey deletes the key associated with the name string if it exists.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) DeleteSymKey(id string) bool {
|
|
|
|
whisper.keyMu.Lock()
|
|
|
|
defer whisper.keyMu.Unlock()
|
|
|
|
if whisper.symKeys[id] != nil {
|
|
|
|
delete(whisper.symKeys, id)
|
2017-11-03 15:29:49 -05:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetSymKey returns the symmetric key associated with the given id.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) GetSymKey(id string) ([]byte, error) {
|
|
|
|
whisper.keyMu.RLock()
|
|
|
|
defer whisper.keyMu.RUnlock()
|
|
|
|
if whisper.symKeys[id] != nil {
|
|
|
|
return whisper.symKeys[id], nil
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("non-existent key ID")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Subscribe installs a new message handler used for filtering, decrypting
|
|
|
|
// and subsequent storing of incoming messages.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) Subscribe(f *Filter) (string, error) {
|
|
|
|
s, err := whisper.filters.Install(f)
|
2018-01-12 05:11:22 -06:00
|
|
|
if err == nil {
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.updateBloomFilter(f)
|
2018-01-12 05:11:22 -06:00
|
|
|
}
|
|
|
|
return s, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// updateBloomFilter recalculates the new value of bloom filter,
|
|
|
|
// and informs the peers if necessary.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) updateBloomFilter(f *Filter) {
|
2018-03-01 09:04:09 -06:00
|
|
|
aggregate := make([]byte, BloomFilterSize)
|
2018-01-12 05:11:22 -06:00
|
|
|
for _, t := range f.Topics {
|
|
|
|
top := BytesToTopic(t)
|
|
|
|
b := TopicToBloom(top)
|
|
|
|
aggregate = addBloom(aggregate, b)
|
|
|
|
}
|
|
|
|
|
2018-03-01 09:04:09 -06:00
|
|
|
if !BloomFilterMatch(whisper.BloomFilter(), aggregate) {
|
2018-01-12 05:11:22 -06:00
|
|
|
// existing bloom filter must be updated
|
2018-01-26 05:45:10 -06:00
|
|
|
aggregate = addBloom(whisper.BloomFilter(), aggregate)
|
|
|
|
whisper.SetBloomFilter(aggregate)
|
2018-01-12 05:11:22 -06:00
|
|
|
}
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetFilter returns the filter by id.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) GetFilter(id string) *Filter {
|
|
|
|
return whisper.filters.Get(id)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Unsubscribe removes an installed message handler.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) Unsubscribe(id string) error {
|
|
|
|
ok := whisper.filters.Uninstall(id)
|
2017-11-03 15:29:49 -05:00
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("Unsubscribe: Invalid ID")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send injects a message into the whisper send queue, to be distributed in the
|
|
|
|
// network in the coming cycles.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) Send(envelope *Envelope) error {
|
2018-02-23 04:10:28 -06:00
|
|
|
ok, err := whisper.add(envelope, false)
|
2018-02-23 07:52:25 -06:00
|
|
|
if err == nil && !ok {
|
2017-11-03 15:29:49 -05:00
|
|
|
return fmt.Errorf("failed to add envelope")
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start implements node.Service, starting the background data propagation thread
|
|
|
|
// of the Whisper protocol.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) Start(*p2p.Server) error {
|
2017-11-03 15:29:49 -05:00
|
|
|
log.Info("started whisper v." + ProtocolVersionStr)
|
2020-04-01 04:35:26 -05:00
|
|
|
whisper.wg.Add(1)
|
2018-01-26 05:45:10 -06:00
|
|
|
go whisper.update()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
|
|
|
numCPU := runtime.NumCPU()
|
|
|
|
for i := 0; i < numCPU; i++ {
|
2020-04-01 04:35:26 -05:00
|
|
|
whisper.wg.Add(1)
|
2018-01-26 05:45:10 -06:00
|
|
|
go whisper.processQueue()
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop implements node.Service, stopping the background data propagation thread
|
|
|
|
// of the Whisper protocol.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) Stop() error {
|
|
|
|
close(whisper.quit)
|
2020-04-01 04:35:26 -05:00
|
|
|
whisper.wg.Wait()
|
2017-11-03 15:29:49 -05:00
|
|
|
log.Info("whisper stopped")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// HandlePeer is called by the underlying P2P layer when the whisper sub-protocol
|
|
|
|
// connection is negotiated.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) HandlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
|
2017-11-03 15:29:49 -05:00
|
|
|
// Create the new peer and start tracking it
|
2018-01-26 05:45:10 -06:00
|
|
|
whisperPeer := newPeer(whisper, peer, rw)
|
2017-11-03 15:29:49 -05:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.peerMu.Lock()
|
|
|
|
whisper.peers[whisperPeer] = struct{}{}
|
|
|
|
whisper.peerMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
|
|
|
defer func() {
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.peerMu.Lock()
|
|
|
|
delete(whisper.peers, whisperPeer)
|
|
|
|
whisper.peerMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
}()
|
|
|
|
|
|
|
|
// Run the peer handshake and state updates
|
|
|
|
if err := whisperPeer.handshake(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
whisperPeer.start()
|
|
|
|
defer whisperPeer.stop()
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
return whisper.runMessageLoop(whisperPeer, rw)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// runMessageLoop reads and processes inbound messages directly to merge into client-global state.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
|
2017-11-03 15:29:49 -05:00
|
|
|
for {
|
|
|
|
// fetch the next packet
|
|
|
|
packet, err := rw.ReadMsg()
|
|
|
|
if err != nil {
|
2018-06-26 03:31:05 -05:00
|
|
|
log.Info("message loop", "peer", p.peer.ID(), "err", err)
|
2017-11-03 15:29:49 -05:00
|
|
|
return err
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
if packet.Size > whisper.MaxMessageSize() {
|
2017-11-03 15:29:49 -05:00
|
|
|
log.Warn("oversized message received", "peer", p.peer.ID())
|
|
|
|
return errors.New("oversized message received")
|
|
|
|
}
|
|
|
|
|
|
|
|
switch packet.Code {
|
|
|
|
case statusCode:
|
|
|
|
// this should not happen, but no need to panic; just ignore this message.
|
|
|
|
log.Warn("unxepected status message received", "peer", p.peer.ID())
|
|
|
|
case messagesCode:
|
|
|
|
// decode the contained envelopes
|
2017-12-21 03:31:44 -06:00
|
|
|
var envelopes []*Envelope
|
|
|
|
if err := packet.Decode(&envelopes); err != nil {
|
|
|
|
log.Warn("failed to decode envelopes, peer will be disconnected", "peer", p.peer.ID(), "err", err)
|
|
|
|
return errors.New("invalid envelopes")
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
2017-12-21 03:31:44 -06:00
|
|
|
|
|
|
|
trouble := false
|
|
|
|
for _, env := range envelopes {
|
2018-09-05 03:57:45 -05:00
|
|
|
cached, err := whisper.add(env, whisper.LightClientMode())
|
2017-12-21 03:31:44 -06:00
|
|
|
if err != nil {
|
|
|
|
trouble = true
|
|
|
|
log.Error("bad envelope received, peer will be disconnected", "peer", p.peer.ID(), "err", err)
|
|
|
|
}
|
|
|
|
if cached {
|
|
|
|
p.mark(env)
|
|
|
|
}
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
2017-12-21 03:31:44 -06:00
|
|
|
|
|
|
|
if trouble {
|
|
|
|
return errors.New("invalid envelope")
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
2017-12-21 08:17:27 -06:00
|
|
|
case powRequirementCode:
|
|
|
|
s := rlp.NewStream(packet.Payload, uint64(packet.Size))
|
|
|
|
i, err := s.Uint()
|
|
|
|
if err != nil {
|
|
|
|
log.Warn("failed to decode powRequirementCode message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
|
|
|
|
return errors.New("invalid powRequirementCode message")
|
|
|
|
}
|
|
|
|
f := math.Float64frombits(i)
|
|
|
|
if math.IsInf(f, 0) || math.IsNaN(f) || f < 0.0 {
|
|
|
|
log.Warn("invalid value in powRequirementCode message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
|
|
|
|
return errors.New("invalid value in powRequirementCode message")
|
|
|
|
}
|
|
|
|
p.powRequirement = f
|
|
|
|
case bloomFilterExCode:
|
2018-01-12 05:11:22 -06:00
|
|
|
var bloom []byte
|
|
|
|
err := packet.Decode(&bloom)
|
2018-03-01 09:04:09 -06:00
|
|
|
if err == nil && len(bloom) != BloomFilterSize {
|
2018-01-12 05:11:22 -06:00
|
|
|
err = fmt.Errorf("wrong bloom filter size %d", len(bloom))
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Warn("failed to decode bloom filter exchange message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
|
|
|
|
return errors.New("invalid bloom filter exchange message")
|
|
|
|
}
|
2018-02-09 09:25:23 -06:00
|
|
|
p.setBloomFilter(bloom)
|
2017-12-21 08:17:27 -06:00
|
|
|
case p2pMessageCode:
|
2017-11-03 15:29:49 -05:00
|
|
|
// peer-to-peer message, sent directly to peer bypassing PoW checks, etc.
|
|
|
|
// this message is not supposed to be forwarded to other peers, and
|
|
|
|
// therefore might not satisfy the PoW, expiry and other requirements.
|
|
|
|
// these messages are only accepted from the trusted peer.
|
|
|
|
if p.trusted {
|
|
|
|
var envelope Envelope
|
|
|
|
if err := packet.Decode(&envelope); err != nil {
|
|
|
|
log.Warn("failed to decode direct message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
|
|
|
|
return errors.New("invalid direct message")
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.postEvent(&envelope, true)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
case p2pRequestCode:
|
|
|
|
// Must be processed if mail server is implemented. Otherwise ignore.
|
2018-01-26 05:45:10 -06:00
|
|
|
if whisper.mailServer != nil {
|
2017-11-03 15:29:49 -05:00
|
|
|
var request Envelope
|
|
|
|
if err := packet.Decode(&request); err != nil {
|
|
|
|
log.Warn("failed to decode p2p request message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
|
|
|
|
return errors.New("invalid p2p request")
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.mailServer.DeliverMail(p, &request)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
default:
|
|
|
|
// New message types might be implemented in the future versions of Whisper.
|
|
|
|
// For forward compatibility, just ignore.
|
|
|
|
}
|
|
|
|
|
|
|
|
packet.Discard()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// add inserts a new envelope into the message pool to be distributed within the
|
|
|
|
// whisper network. It also inserts the envelope into the expiration pool at the
|
|
|
|
// appropriate time-stamp. In case of error, connection should be dropped.
|
2018-02-23 04:10:28 -06:00
|
|
|
// param isP2P indicates whether the message is peer-to-peer (should not be forwarded).
|
|
|
|
func (whisper *Whisper) add(envelope *Envelope, isP2P bool) (bool, error) {
|
2017-11-03 15:29:49 -05:00
|
|
|
now := uint32(time.Now().Unix())
|
|
|
|
sent := envelope.Expiry - envelope.TTL
|
|
|
|
|
|
|
|
if sent > now {
|
2018-01-12 05:11:22 -06:00
|
|
|
if sent-DefaultSyncAllowance > now {
|
2017-11-03 15:29:49 -05:00
|
|
|
return false, fmt.Errorf("envelope created in the future [%x]", envelope.Hash())
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
// recalculate PoW, adjusted for the time difference, plus one second for latency
|
|
|
|
envelope.calculatePoW(sent - now + 1)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
if envelope.Expiry < now {
|
2018-01-12 05:11:22 -06:00
|
|
|
if envelope.Expiry+DefaultSyncAllowance*2 < now {
|
2017-11-03 15:29:49 -05:00
|
|
|
return false, fmt.Errorf("very old message")
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
log.Debug("expired envelope dropped", "hash", envelope.Hash().Hex())
|
|
|
|
return false, nil // drop envelope without error
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
if uint32(envelope.size()) > whisper.MaxMessageSize() {
|
2017-11-03 15:29:49 -05:00
|
|
|
return false, fmt.Errorf("huge messages are not allowed [%x]", envelope.Hash())
|
|
|
|
}
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
if envelope.PoW() < whisper.MinPow() {
|
2018-01-12 05:11:22 -06:00
|
|
|
// maybe the value was recently changed, and the peers did not adjust yet.
|
|
|
|
// in this case the previous value is retrieved by MinPowTolerance()
|
|
|
|
// for a short period of peer synchronization.
|
2018-01-26 05:45:10 -06:00
|
|
|
if envelope.PoW() < whisper.MinPowTolerance() {
|
2018-01-12 05:11:22 -06:00
|
|
|
return false, fmt.Errorf("envelope with low PoW received: PoW=%f, hash=[%v]", envelope.PoW(), envelope.Hash().Hex())
|
|
|
|
}
|
|
|
|
}
|
2017-12-21 08:17:27 -06:00
|
|
|
|
2018-03-01 09:04:09 -06:00
|
|
|
if !BloomFilterMatch(whisper.BloomFilter(), envelope.Bloom()) {
|
2018-01-12 05:11:22 -06:00
|
|
|
// maybe the value was recently changed, and the peers did not adjust yet.
|
|
|
|
// in this case the previous value is retrieved by BloomFilterTolerance()
|
|
|
|
// for a short period of peer synchronization.
|
2018-03-01 09:04:09 -06:00
|
|
|
if !BloomFilterMatch(whisper.BloomFilterTolerance(), envelope.Bloom()) {
|
2018-01-12 05:11:22 -06:00
|
|
|
return false, fmt.Errorf("envelope does not match bloom filter, hash=[%v], bloom: \n%x \n%x \n%x",
|
2018-01-26 05:45:10 -06:00
|
|
|
envelope.Hash().Hex(), whisper.BloomFilter(), envelope.Bloom(), envelope.Topic)
|
2018-01-12 05:11:22 -06:00
|
|
|
}
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
hash := envelope.Hash()
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.poolMu.Lock()
|
|
|
|
_, alreadyCached := whisper.envelopes[hash]
|
2017-11-03 15:29:49 -05:00
|
|
|
if !alreadyCached {
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.envelopes[hash] = envelope
|
|
|
|
if whisper.expirations[envelope.Expiry] == nil {
|
2018-07-16 02:54:19 -05:00
|
|
|
whisper.expirations[envelope.Expiry] = mapset.NewThreadUnsafeSet()
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
2018-07-16 02:54:19 -05:00
|
|
|
if !whisper.expirations[envelope.Expiry].Contains(hash) {
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.expirations[envelope.Expiry].Add(hash)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
}
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.poolMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
|
|
|
if alreadyCached {
|
|
|
|
log.Trace("whisper envelope already cached", "hash", envelope.Hash().Hex())
|
|
|
|
} else {
|
|
|
|
log.Trace("cached whisper envelope", "hash", envelope.Hash().Hex())
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.statsMu.Lock()
|
|
|
|
whisper.stats.memoryUsed += envelope.size()
|
|
|
|
whisper.statsMu.Unlock()
|
2018-02-23 04:10:28 -06:00
|
|
|
whisper.postEvent(envelope, isP2P) // notify the local node about the new message
|
2018-01-26 05:45:10 -06:00
|
|
|
if whisper.mailServer != nil {
|
|
|
|
whisper.mailServer.Archive(envelope)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// postEvent queues the message for further processing.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) postEvent(envelope *Envelope, isP2P bool) {
|
2017-12-08 09:08:56 -06:00
|
|
|
if isP2P {
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.p2pMsgQueue <- envelope
|
2017-12-08 09:08:56 -06:00
|
|
|
} else {
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.checkOverflow()
|
|
|
|
whisper.messageQueue <- envelope
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// checkOverflow checks if message queue overflow occurs and reports it if necessary.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) checkOverflow() {
|
|
|
|
queueSize := len(whisper.messageQueue)
|
2017-11-03 15:29:49 -05:00
|
|
|
|
|
|
|
if queueSize == messageQueueLimit {
|
2018-01-26 05:45:10 -06:00
|
|
|
if !whisper.Overflow() {
|
|
|
|
whisper.settings.Store(overflowIdx, true)
|
2017-11-03 15:29:49 -05:00
|
|
|
log.Warn("message queue overflow")
|
|
|
|
}
|
|
|
|
} else if queueSize <= messageQueueLimit/2 {
|
2018-01-26 05:45:10 -06:00
|
|
|
if whisper.Overflow() {
|
|
|
|
whisper.settings.Store(overflowIdx, false)
|
2017-11-03 15:29:49 -05:00
|
|
|
log.Warn("message queue overflow fixed (back to normal)")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// processQueue delivers the messages to the watchers during the lifetime of the whisper node.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) processQueue() {
|
2020-04-01 04:35:26 -05:00
|
|
|
defer whisper.wg.Done()
|
2017-11-03 15:29:49 -05:00
|
|
|
var e *Envelope
|
|
|
|
for {
|
|
|
|
select {
|
2018-01-26 05:45:10 -06:00
|
|
|
case <-whisper.quit:
|
2017-11-03 15:29:49 -05:00
|
|
|
return
|
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
case e = <-whisper.messageQueue:
|
|
|
|
whisper.filters.NotifyWatchers(e, false)
|
2017-11-03 15:29:49 -05:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
case e = <-whisper.p2pMsgQueue:
|
|
|
|
whisper.filters.NotifyWatchers(e, true)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// update loops until the lifetime of the whisper node, updating its internal
|
|
|
|
// state by expiring stale messages from the pool.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) update() {
|
2020-04-01 04:35:26 -05:00
|
|
|
defer whisper.wg.Done()
|
2017-11-03 15:29:49 -05:00
|
|
|
// Start a ticker to check for expirations
|
|
|
|
expire := time.NewTicker(expirationCycle)
|
|
|
|
|
|
|
|
// Repeat updates until termination is requested
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-expire.C:
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.expire()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
case <-whisper.quit:
|
2017-11-03 15:29:49 -05:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// expire iterates over all the expiration timestamps, removing all stale
|
|
|
|
// messages from the pools.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) expire() {
|
|
|
|
whisper.poolMu.Lock()
|
|
|
|
defer whisper.poolMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.statsMu.Lock()
|
|
|
|
defer whisper.statsMu.Unlock()
|
|
|
|
whisper.stats.reset()
|
2017-11-03 15:29:49 -05:00
|
|
|
now := uint32(time.Now().Unix())
|
2018-01-26 05:45:10 -06:00
|
|
|
for expiry, hashSet := range whisper.expirations {
|
2017-11-03 15:29:49 -05:00
|
|
|
if expiry < now {
|
|
|
|
// Dump all expired messages and remove timestamp
|
|
|
|
hashSet.Each(func(v interface{}) bool {
|
2018-01-26 05:45:10 -06:00
|
|
|
sz := whisper.envelopes[v.(common.Hash)].size()
|
|
|
|
delete(whisper.envelopes, v.(common.Hash))
|
|
|
|
whisper.stats.messagesCleared++
|
|
|
|
whisper.stats.memoryCleared += sz
|
|
|
|
whisper.stats.memoryUsed -= sz
|
2018-08-29 05:56:13 -05:00
|
|
|
return false
|
2017-11-03 15:29:49 -05:00
|
|
|
})
|
2018-01-26 05:45:10 -06:00
|
|
|
whisper.expirations[expiry].Clear()
|
|
|
|
delete(whisper.expirations, expiry)
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stats returns the whisper node statistics.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) Stats() Statistics {
|
|
|
|
whisper.statsMu.Lock()
|
|
|
|
defer whisper.statsMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
return whisper.stats
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Envelopes retrieves all the messages currently pooled by the node.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) Envelopes() []*Envelope {
|
|
|
|
whisper.poolMu.RLock()
|
|
|
|
defer whisper.poolMu.RUnlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
all := make([]*Envelope, 0, len(whisper.envelopes))
|
|
|
|
for _, envelope := range whisper.envelopes {
|
2017-11-03 15:29:49 -05:00
|
|
|
all = append(all, envelope)
|
|
|
|
}
|
|
|
|
return all
|
|
|
|
}
|
|
|
|
|
|
|
|
// isEnvelopeCached checks if envelope with specific hash has already been received and cached.
|
2018-01-26 05:45:10 -06:00
|
|
|
func (whisper *Whisper) isEnvelopeCached(hash common.Hash) bool {
|
|
|
|
whisper.poolMu.Lock()
|
|
|
|
defer whisper.poolMu.Unlock()
|
2017-11-03 15:29:49 -05:00
|
|
|
|
2018-01-26 05:45:10 -06:00
|
|
|
_, exist := whisper.envelopes[hash]
|
2017-11-03 15:29:49 -05:00
|
|
|
return exist
|
|
|
|
}
|
|
|
|
|
|
|
|
// reset resets the node's statistics after each expiry cycle.
|
|
|
|
func (s *Statistics) reset() {
|
|
|
|
s.cycles++
|
|
|
|
s.totalMessagesCleared += s.messagesCleared
|
|
|
|
|
|
|
|
s.memoryCleared = 0
|
|
|
|
s.messagesCleared = 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// ValidatePublicKey checks the format of the given public key.
|
|
|
|
func ValidatePublicKey(k *ecdsa.PublicKey) bool {
|
|
|
|
return k != nil && k.X != nil && k.Y != nil && k.X.Sign() != 0 && k.Y.Sign() != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// validatePrivateKey checks the format of the given private key.
|
|
|
|
func validatePrivateKey(k *ecdsa.PrivateKey) bool {
|
|
|
|
if k == nil || k.D == nil || k.D.Sign() == 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return ValidatePublicKey(&k.PublicKey)
|
|
|
|
}
|
|
|
|
|
2018-01-30 02:55:08 -06:00
|
|
|
// validateDataIntegrity returns false if the data have the wrong or contains all zeros,
|
|
|
|
// which is the simplest and the most common bug.
|
|
|
|
func validateDataIntegrity(k []byte, expectedSize int) bool {
|
|
|
|
if len(k) != expectedSize {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if expectedSize > 3 && containsOnlyZeros(k) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
2017-11-03 15:29:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// containsOnlyZeros checks if the data contain only zeros.
|
|
|
|
func containsOnlyZeros(data []byte) bool {
|
|
|
|
for _, b := range data {
|
|
|
|
if b != 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// bytesToUintLittleEndian converts the slice to 64-bit unsigned integer.
|
|
|
|
func bytesToUintLittleEndian(b []byte) (res uint64) {
|
|
|
|
mul := uint64(1)
|
|
|
|
for i := 0; i < len(b); i++ {
|
|
|
|
res += uint64(b[i]) * mul
|
|
|
|
mul *= 256
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
|
|
|
// BytesToUintBigEndian converts the slice to 64-bit unsigned integer.
|
|
|
|
func BytesToUintBigEndian(b []byte) (res uint64) {
|
|
|
|
for i := 0; i < len(b); i++ {
|
|
|
|
res *= 256
|
|
|
|
res += uint64(b[i])
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
|
|
|
// GenerateRandomID generates a random string, which is then returned to be used as a key id
|
|
|
|
func GenerateRandomID() (id string, err error) {
|
2018-01-30 02:55:08 -06:00
|
|
|
buf, err := generateSecureRandomData(keyIDSize)
|
2017-11-03 15:29:49 -05:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2018-01-30 02:55:08 -06:00
|
|
|
if !validateDataIntegrity(buf, keyIDSize) {
|
2017-11-03 15:29:49 -05:00
|
|
|
return "", fmt.Errorf("error in generateRandomID: crypto/rand failed to generate random data")
|
|
|
|
}
|
|
|
|
id = common.Bytes2Hex(buf)
|
|
|
|
return id, err
|
|
|
|
}
|
2018-01-12 05:11:22 -06:00
|
|
|
|
|
|
|
func isFullNode(bloom []byte) bool {
|
|
|
|
if bloom == nil {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
for _, b := range bloom {
|
|
|
|
if b != 255 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2018-03-01 09:04:09 -06:00
|
|
|
func BloomFilterMatch(filter, sample []byte) bool {
|
2018-01-12 05:11:22 -06:00
|
|
|
if filter == nil {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2018-03-01 09:04:09 -06:00
|
|
|
for i := 0; i < BloomFilterSize; i++ {
|
2018-01-12 05:11:22 -06:00
|
|
|
f := filter[i]
|
|
|
|
s := sample[i]
|
|
|
|
if (f | s) != f {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func addBloom(a, b []byte) []byte {
|
2018-03-01 09:04:09 -06:00
|
|
|
c := make([]byte, BloomFilterSize)
|
|
|
|
for i := 0; i < BloomFilterSize; i++ {
|
2018-01-12 05:11:22 -06:00
|
|
|
c[i] = a[i] | b[i]
|
|
|
|
}
|
|
|
|
return c
|
|
|
|
}
|