2016-10-29 07:11:37 -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 whisperv5
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"crypto/ecdsa"
|
|
|
|
crand "crypto/rand"
|
|
|
|
"crypto/sha256"
|
|
|
|
"fmt"
|
2016-12-19 17:58:01 -06:00
|
|
|
"runtime"
|
2016-10-29 07:11:37 -05:00
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
|
|
|
"github.com/ethereum/go-ethereum/crypto"
|
2017-02-22 06:10:07 -06:00
|
|
|
"github.com/ethereum/go-ethereum/log"
|
2016-10-29 07:11:37 -05:00
|
|
|
"github.com/ethereum/go-ethereum/p2p"
|
2017-02-14 08:44:47 -06:00
|
|
|
"github.com/ethereum/go-ethereum/rpc"
|
2017-04-09 16:49:22 -05:00
|
|
|
"github.com/syndtr/goleveldb/leveldb/errors"
|
2016-10-29 07:11:37 -05:00
|
|
|
"golang.org/x/crypto/pbkdf2"
|
2017-06-21 04:15:47 -05:00
|
|
|
"golang.org/x/sync/syncmap"
|
2016-10-29 07:11:37 -05:00
|
|
|
set "gopkg.in/fatih/set.v0"
|
|
|
|
)
|
|
|
|
|
2017-02-23 11:46:32 -06:00
|
|
|
type Statistics struct {
|
2017-04-09 16:49:22 -05:00
|
|
|
messagesCleared int
|
|
|
|
memoryCleared int
|
|
|
|
memoryUsed int
|
|
|
|
cycles int
|
|
|
|
totalMessagesCleared int
|
2017-02-23 11:46:32 -06:00
|
|
|
}
|
|
|
|
|
2017-06-13 04:49:07 -05:00
|
|
|
const (
|
2017-06-21 04:15:47 -05:00
|
|
|
minPowIdx = iota // Minimal PoW required by the whisper node
|
|
|
|
maxMsgSizeIdx = iota // Maximal message length allowed by the whisper node
|
|
|
|
overflowIdx = iota // Indicator of message queue overflow
|
2017-06-13 04:49:07 -05:00
|
|
|
)
|
|
|
|
|
2016-10-29 07:11:37 -05:00
|
|
|
// Whisper represents a dark communication interface through the Ethereum
|
|
|
|
// network, using its very own P2P communication layer.
|
|
|
|
type Whisper struct {
|
2017-04-09 16:49:22 -05:00
|
|
|
protocol p2p.Protocol // Protocol description and parameters
|
|
|
|
filters *Filters // Message filters installed with Subscribe function
|
2016-10-29 07:11:37 -05:00
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
privateKeys map[string]*ecdsa.PrivateKey // Private key storage
|
|
|
|
symKeys map[string][]byte // Symmetric key storage
|
|
|
|
keyMu sync.RWMutex // Mutex associated with key storages
|
2016-10-29 07:11:37 -05:00
|
|
|
|
2017-06-13 04:49:07 -05:00
|
|
|
poolMu sync.RWMutex // Mutex to sync the message and expiration pools
|
2017-04-09 16:49:22 -05:00
|
|
|
envelopes map[common.Hash]*Envelope // Pool of envelopes currently tracked by this node
|
|
|
|
expirations map[uint32]*set.SetNonTS // Message expiration pool
|
2016-10-29 07:11:37 -05:00
|
|
|
|
|
|
|
peerMu sync.RWMutex // Mutex to sync the active peer set
|
2017-06-13 04:49:07 -05:00
|
|
|
peers map[*Peer]struct{} // Set of currently active peers
|
2016-10-29 07:11:37 -05:00
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
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
|
2016-10-29 07:11:37 -05:00
|
|
|
|
2017-06-21 04:15:47 -05:00
|
|
|
settings syncmap.Map // holds configuration settings that can be dynamically changed
|
2016-12-19 17:58:01 -06:00
|
|
|
|
2017-06-13 04:49:07 -05:00
|
|
|
statsMu sync.Mutex // guard stats
|
|
|
|
stats Statistics // Statistics of whisper node
|
2017-02-23 11:46:32 -06:00
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
mailServer MailServer // MailServer interface
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// New creates a Whisper client ready to communicate through the Ethereum P2P network.
|
2017-06-13 04:49:07 -05:00
|
|
|
func New(cfg *Config) *Whisper {
|
2017-06-21 03:24:34 -05:00
|
|
|
if cfg == nil {
|
|
|
|
cfg = &DefaultConfig
|
|
|
|
}
|
2017-06-21 03:32:36 -05:00
|
|
|
|
2016-10-29 07:11:37 -05:00
|
|
|
whisper := &Whisper{
|
2016-12-19 17:58:01 -06:00
|
|
|
privateKeys: make(map[string]*ecdsa.PrivateKey),
|
|
|
|
symKeys: make(map[string][]byte),
|
|
|
|
envelopes: make(map[common.Hash]*Envelope),
|
|
|
|
expirations: make(map[uint32]*set.SetNonTS),
|
|
|
|
peers: make(map[*Peer]struct{}),
|
|
|
|
messageQueue: make(chan *Envelope, messageQueueLimit),
|
|
|
|
p2pMsgQueue: make(chan *Envelope, messageQueueLimit),
|
|
|
|
quit: make(chan struct{}),
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2017-06-13 04:49:07 -05:00
|
|
|
|
2016-10-29 07:11:37 -05:00
|
|
|
whisper.filters = NewFilters(whisper)
|
|
|
|
|
2017-06-21 04:15:47 -05:00
|
|
|
whisper.settings.Store(minPowIdx, cfg.MinimumAcceptedPOW)
|
|
|
|
whisper.settings.Store(maxMsgSizeIdx, cfg.MaxMessageSize)
|
|
|
|
whisper.settings.Store(overflowIdx, false)
|
2017-06-13 04:49:07 -05:00
|
|
|
|
2016-10-29 07:11:37 -05:00
|
|
|
// p2p whisper sub protocol handler
|
|
|
|
whisper.protocol = p2p.Protocol{
|
|
|
|
Name: ProtocolName,
|
|
|
|
Version: uint(ProtocolVersion),
|
|
|
|
Length: NumberOfMessageCodes,
|
|
|
|
Run: whisper.HandlePeer,
|
2017-06-13 04:49:07 -05:00
|
|
|
NodeInfo: func() interface{} {
|
|
|
|
return map[string]interface{}{
|
|
|
|
"version": ProtocolVersionStr,
|
|
|
|
"maxMessageSize": whisper.MaxMessageSize(),
|
|
|
|
"minimumPoW": whisper.MinPow(),
|
|
|
|
}
|
|
|
|
},
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
return whisper
|
|
|
|
}
|
|
|
|
|
2017-06-13 04:49:07 -05:00
|
|
|
func (w *Whisper) MinPow() float64 {
|
2017-06-21 04:15:47 -05:00
|
|
|
val, _ := w.settings.Load(minPowIdx)
|
|
|
|
return val.(float64)
|
2017-06-13 04:49:07 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// MaxMessageSize returns the maximum accepted message size.
|
|
|
|
func (w *Whisper) MaxMessageSize() uint32 {
|
2017-06-21 04:15:47 -05:00
|
|
|
val, _ := w.settings.Load(maxMsgSizeIdx)
|
|
|
|
return val.(uint32)
|
2017-06-13 04:49:07 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Overflow returns an indication if the message queue is full.
|
|
|
|
func (w *Whisper) Overflow() bool {
|
2017-06-21 04:15:47 -05:00
|
|
|
val, _ := w.settings.Load(overflowIdx)
|
|
|
|
return val.(bool)
|
2017-06-13 04:49:07 -05:00
|
|
|
}
|
|
|
|
|
2017-02-14 08:44:47 -06:00
|
|
|
// APIs returns the RPC descriptors the Whisper implementation offers
|
|
|
|
func (w *Whisper) APIs() []rpc.API {
|
|
|
|
return []rpc.API{
|
|
|
|
{
|
|
|
|
Namespace: ProtocolName,
|
|
|
|
Version: ProtocolVersionStr,
|
|
|
|
Service: NewPublicWhisperAPI(w),
|
|
|
|
Public: true,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// RegisterServer registers MailServer interface.
|
|
|
|
// MailServer will process all the incoming messages with p2pRequestCode.
|
2017-02-14 08:44:47 -06:00
|
|
|
func (w *Whisper) RegisterServer(server MailServer) {
|
|
|
|
w.mailServer = server
|
|
|
|
}
|
|
|
|
|
2016-10-29 07:11:37 -05:00
|
|
|
// Protocols returns the whisper sub-protocols ran by this particular client.
|
|
|
|
func (w *Whisper) Protocols() []p2p.Protocol {
|
|
|
|
return []p2p.Protocol{w.protocol}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Version returns the whisper sub-protocols version number.
|
|
|
|
func (w *Whisper) Version() uint {
|
|
|
|
return w.protocol.Version
|
|
|
|
}
|
|
|
|
|
2017-06-13 04:49:07 -05:00
|
|
|
// SetMaxMessageSize sets the maximal message size allowed by this node
|
|
|
|
func (w *Whisper) SetMaxMessageSize(size uint32) error {
|
|
|
|
if size > MaxMessageSize {
|
|
|
|
return fmt.Errorf("message size too large [%d>%d]", size, MaxMessageSize)
|
2017-04-09 16:49:22 -05:00
|
|
|
}
|
2017-11-10 11:06:45 -06:00
|
|
|
w.settings.Store(maxMsgSizeIdx, size)
|
2017-04-09 16:49:22 -05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetMinimumPoW sets the minimal PoW required by this node
|
|
|
|
func (w *Whisper) SetMinimumPoW(val float64) error {
|
|
|
|
if val <= 0.0 {
|
|
|
|
return fmt.Errorf("invalid PoW: %f", val)
|
|
|
|
}
|
2017-06-21 04:15:47 -05:00
|
|
|
w.settings.Store(minPowIdx, val)
|
2017-04-09 16:49:22 -05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// getPeer retrieves peer by ID
|
2016-10-29 07:11:37 -05:00
|
|
|
func (w *Whisper) getPeer(peerID []byte) (*Peer, error) {
|
|
|
|
w.peerMu.Lock()
|
|
|
|
defer w.peerMu.Unlock()
|
2017-01-06 08:52:03 -06:00
|
|
|
for p := range w.peers {
|
2016-10-29 07:11:37 -05:00
|
|
|
id := p.peer.ID()
|
|
|
|
if bytes.Equal(peerID, id[:]) {
|
|
|
|
return p, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("Could not find peer with ID: %x", peerID)
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// AllowP2PMessagesFromPeer marks specific peer trusted,
|
|
|
|
// which will allow it to send historic (expired) messages.
|
|
|
|
func (w *Whisper) AllowP2PMessagesFromPeer(peerID []byte) error {
|
2016-10-29 07:11:37 -05:00
|
|
|
p, err := w.getPeer(peerID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
p.trusted = true
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// 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.
|
2017-01-31 04:16:20 -06:00
|
|
|
func (w *Whisper) RequestHistoricMessages(peerID []byte, envelope *Envelope) error {
|
2016-10-29 07:11:37 -05:00
|
|
|
p, err := w.getPeer(peerID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
p.trusted = true
|
2017-01-31 04:16:20 -06:00
|
|
|
return p2p.Send(p.ws, p2pRequestCode, envelope)
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// SendP2PMessage sends a peer-to-peer message to a specific peer.
|
2016-10-29 07:11:37 -05:00
|
|
|
func (w *Whisper) SendP2PMessage(peerID []byte, envelope *Envelope) error {
|
|
|
|
p, err := w.getPeer(peerID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-04-09 16:49:22 -05:00
|
|
|
return w.SendP2PDirect(p, envelope)
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// SendP2PDirect sends a peer-to-peer message to a specific peer.
|
2017-01-31 04:16:20 -06:00
|
|
|
func (w *Whisper) SendP2PDirect(peer *Peer, envelope *Envelope) error {
|
|
|
|
return p2p.Send(peer.ws, p2pCode, envelope)
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -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.
|
|
|
|
func (w *Whisper) NewKeyPair() (string, error) {
|
2016-10-29 07:11:37 -05:00
|
|
|
key, err := crypto.GenerateKey()
|
|
|
|
if err != nil || !validatePrivateKey(key) {
|
|
|
|
key, err = crypto.GenerateKey() // retry once
|
|
|
|
}
|
|
|
|
if err != nil {
|
2017-04-09 16:49:22 -05:00
|
|
|
return "", err
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
if !validatePrivateKey(key) {
|
2017-04-09 16:49:22 -05:00
|
|
|
return "", fmt.Errorf("failed to generate valid key")
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2017-04-09 16:49:22 -05:00
|
|
|
|
|
|
|
id, err := GenerateRandomID()
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate ID: %s", err)
|
|
|
|
}
|
|
|
|
|
2016-10-29 07:11:37 -05:00
|
|
|
w.keyMu.Lock()
|
|
|
|
defer w.keyMu.Unlock()
|
2017-04-09 16:49:22 -05:00
|
|
|
|
|
|
|
if w.privateKeys[id] != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate unique ID")
|
|
|
|
}
|
|
|
|
w.privateKeys[id] = key
|
|
|
|
return id, nil
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// DeleteKeyPair deletes the specified key if it exists.
|
|
|
|
func (w *Whisper) DeleteKeyPair(key string) bool {
|
2016-10-29 07:11:37 -05:00
|
|
|
w.keyMu.Lock()
|
|
|
|
defer w.keyMu.Unlock()
|
2017-04-09 16:49:22 -05:00
|
|
|
|
|
|
|
if w.privateKeys[key] != nil {
|
|
|
|
delete(w.privateKeys, key)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-06-13 04:49:07 -05:00
|
|
|
// AddKeyPair imports a asymmetric private key and returns it identifier.
|
|
|
|
func (w *Whisper) AddKeyPair(key *ecdsa.PrivateKey) (string, error) {
|
|
|
|
id, err := GenerateRandomID()
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate ID: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
w.keyMu.Lock()
|
|
|
|
w.privateKeys[id] = key
|
|
|
|
w.keyMu.Unlock()
|
|
|
|
|
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// HasKeyPair checks if the the whisper node is configured with the private key
|
2016-10-29 07:11:37 -05:00
|
|
|
// of the specified public pair.
|
2017-04-09 16:49:22 -05:00
|
|
|
func (w *Whisper) HasKeyPair(id string) bool {
|
2016-10-29 07:11:37 -05:00
|
|
|
w.keyMu.RLock()
|
|
|
|
defer w.keyMu.RUnlock()
|
2017-04-09 16:49:22 -05:00
|
|
|
return w.privateKeys[id] != nil
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// GetPrivateKey retrieves the private key of the specified identity.
|
|
|
|
func (w *Whisper) GetPrivateKey(id string) (*ecdsa.PrivateKey, error) {
|
2016-10-29 07:11:37 -05:00
|
|
|
w.keyMu.RLock()
|
|
|
|
defer w.keyMu.RUnlock()
|
2017-04-09 16:49:22 -05:00
|
|
|
key := w.privateKeys[id]
|
|
|
|
if key == nil {
|
|
|
|
return nil, fmt.Errorf("invalid id")
|
|
|
|
}
|
|
|
|
return key, nil
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// 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.
|
|
|
|
func (w *Whisper) GenerateSymKey() (string, error) {
|
2017-04-26 14:05:48 -05:00
|
|
|
key := make([]byte, aesKeyLength)
|
|
|
|
_, err := crand.Read(key)
|
2016-10-29 07:11:37 -05:00
|
|
|
if err != nil {
|
2017-04-09 16:49:22 -05:00
|
|
|
return "", err
|
2017-04-26 14:05:48 -05:00
|
|
|
} else if !validateSymmetricKey(key) {
|
2017-04-09 16:49:22 -05:00
|
|
|
return "", fmt.Errorf("error in GenerateSymKey: crypto/rand failed to generate random data")
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
id, err := GenerateRandomID()
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate ID: %s", err)
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
w.keyMu.Lock()
|
|
|
|
defer w.keyMu.Unlock()
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
if w.symKeys[id] != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate unique ID")
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2017-04-26 14:05:48 -05:00
|
|
|
w.symKeys[id] = key
|
2017-04-09 16:49:22 -05:00
|
|
|
return id, nil
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// AddSymKeyDirect stores the key, and returns its id.
|
|
|
|
func (w *Whisper) AddSymKeyDirect(key []byte) (string, error) {
|
|
|
|
if len(key) != aesKeyLength {
|
|
|
|
return "", fmt.Errorf("wrong key size: %d", len(key))
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
id, err := GenerateRandomID()
|
2016-10-29 07:11:37 -05:00
|
|
|
if err != nil {
|
2017-04-09 16:49:22 -05:00
|
|
|
return "", fmt.Errorf("failed to generate ID: %s", err)
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
w.keyMu.Lock()
|
|
|
|
defer w.keyMu.Unlock()
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
if w.symKeys[id] != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate unique ID")
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2017-04-09 16:49:22 -05:00
|
|
|
w.symKeys[id] = key
|
|
|
|
return id, nil
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// AddSymKeyFromPassword generates the key from password, stores it, and returns its id.
|
|
|
|
func (w *Whisper) AddSymKeyFromPassword(password string) (string, error) {
|
|
|
|
id, err := GenerateRandomID()
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("failed to generate ID: %s", err)
|
|
|
|
}
|
|
|
|
if w.HasSymKey(id) {
|
|
|
|
return "", fmt.Errorf("failed to generate unique ID")
|
|
|
|
}
|
|
|
|
|
|
|
|
derived, err := deriveKeyMaterial([]byte(password), EnvelopeVersion)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
w.keyMu.Lock()
|
|
|
|
defer w.keyMu.Unlock()
|
|
|
|
|
|
|
|
// double check is necessary, because deriveKeyMaterial() is very slow
|
|
|
|
if w.symKeys[id] != nil {
|
|
|
|
return "", fmt.Errorf("critical error: failed to generate unique ID")
|
|
|
|
}
|
|
|
|
w.symKeys[id] = derived
|
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// HasSymKey returns true if there is a key associated with the given id.
|
|
|
|
// Otherwise returns false.
|
|
|
|
func (w *Whisper) HasSymKey(id string) bool {
|
2016-10-29 07:11:37 -05:00
|
|
|
w.keyMu.RLock()
|
|
|
|
defer w.keyMu.RUnlock()
|
2017-04-09 16:49:22 -05:00
|
|
|
return w.symKeys[id] != nil
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// DeleteSymKey deletes the key associated with the name string if it exists.
|
|
|
|
func (w *Whisper) DeleteSymKey(id string) bool {
|
2016-10-29 07:11:37 -05:00
|
|
|
w.keyMu.Lock()
|
|
|
|
defer w.keyMu.Unlock()
|
2017-04-09 16:49:22 -05:00
|
|
|
if w.symKeys[id] != nil {
|
|
|
|
delete(w.symKeys, id)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// GetSymKey returns the symmetric key associated with the given id.
|
|
|
|
func (w *Whisper) GetSymKey(id string) ([]byte, error) {
|
2016-10-29 07:11:37 -05:00
|
|
|
w.keyMu.RLock()
|
|
|
|
defer w.keyMu.RUnlock()
|
2017-04-09 16:49:22 -05:00
|
|
|
if w.symKeys[id] != nil {
|
|
|
|
return w.symKeys[id], nil
|
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("non-existent key ID")
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// Subscribe installs a new message handler used for filtering, decrypting
|
|
|
|
// and subsequent storing of incoming messages.
|
|
|
|
func (w *Whisper) Subscribe(f *Filter) (string, error) {
|
2016-10-29 07:11:37 -05:00
|
|
|
return w.filters.Install(f)
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// GetFilter returns the filter by id.
|
2017-02-23 02:41:47 -06:00
|
|
|
func (w *Whisper) GetFilter(id string) *Filter {
|
2016-10-29 07:11:37 -05:00
|
|
|
return w.filters.Get(id)
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// Unsubscribe removes an installed message handler.
|
|
|
|
func (w *Whisper) Unsubscribe(id string) error {
|
|
|
|
ok := w.filters.Uninstall(id)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("Unsubscribe: Invalid ID")
|
|
|
|
}
|
|
|
|
return nil
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Send injects a message into the whisper send queue, to be distributed in the
|
|
|
|
// network in the coming cycles.
|
|
|
|
func (w *Whisper) Send(envelope *Envelope) error {
|
2017-04-09 16:49:22 -05:00
|
|
|
ok, err := w.add(envelope)
|
2017-04-26 14:05:48 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-04-09 16:49:22 -05:00
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("failed to add envelope")
|
|
|
|
}
|
2017-02-23 11:46:32 -06:00
|
|
|
return err
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start implements node.Service, starting the background data propagation thread
|
|
|
|
// of the Whisper protocol.
|
|
|
|
func (w *Whisper) Start(*p2p.Server) error {
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Info("started whisper v." + ProtocolVersionStr)
|
2016-10-29 07:11:37 -05:00
|
|
|
go w.update()
|
2016-12-19 17:58:01 -06:00
|
|
|
|
|
|
|
numCPU := runtime.NumCPU()
|
|
|
|
for i := 0; i < numCPU; i++ {
|
|
|
|
go w.processQueue()
|
|
|
|
}
|
|
|
|
|
2016-10-29 07:11:37 -05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop implements node.Service, stopping the background data propagation thread
|
|
|
|
// of the Whisper protocol.
|
|
|
|
func (w *Whisper) Stop() error {
|
|
|
|
close(w.quit)
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Info("whisper stopped")
|
2016-10-29 07:11:37 -05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// HandlePeer is called by the underlying P2P layer when the whisper sub-protocol
|
2016-10-29 07:11:37 -05:00
|
|
|
// connection is negotiated.
|
2018-05-02 01:17:17 -05:00
|
|
|
func (w *Whisper) HandlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
|
2016-10-29 07:11:37 -05:00
|
|
|
// Create the new peer and start tracking it
|
2018-05-02 01:17:17 -05:00
|
|
|
whisperPeer := newPeer(w, peer, rw)
|
2016-10-29 07:11:37 -05:00
|
|
|
|
2018-05-02 01:17:17 -05:00
|
|
|
w.peerMu.Lock()
|
|
|
|
w.peers[whisperPeer] = struct{}{}
|
|
|
|
w.peerMu.Unlock()
|
2016-10-29 07:11:37 -05:00
|
|
|
|
|
|
|
defer func() {
|
2018-05-02 01:17:17 -05:00
|
|
|
w.peerMu.Lock()
|
|
|
|
delete(w.peers, whisperPeer)
|
|
|
|
w.peerMu.Unlock()
|
2016-10-29 07:11:37 -05:00
|
|
|
}()
|
|
|
|
|
|
|
|
// Run the peer handshake and state updates
|
|
|
|
if err := whisperPeer.handshake(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
whisperPeer.start()
|
|
|
|
defer whisperPeer.stop()
|
|
|
|
|
2018-05-02 01:17:17 -05:00
|
|
|
return w.runMessageLoop(whisperPeer, rw)
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// runMessageLoop reads and processes inbound messages directly to merge into client-global state.
|
2018-05-02 01:17:17 -05:00
|
|
|
func (w *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
|
2016-10-29 07:11:37 -05:00
|
|
|
for {
|
|
|
|
// fetch the next packet
|
|
|
|
packet, err := rw.ReadMsg()
|
|
|
|
if err != nil {
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Warn("message loop", "peer", p.peer.ID(), "err", err)
|
2016-10-29 07:11:37 -05:00
|
|
|
return err
|
|
|
|
}
|
2018-05-02 01:17:17 -05:00
|
|
|
if packet.Size > w.MaxMessageSize() {
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Warn("oversized message received", "peer", p.peer.ID())
|
|
|
|
return errors.New("oversized message received")
|
|
|
|
}
|
2016-10-29 07:11:37 -05:00
|
|
|
|
|
|
|
switch packet.Code {
|
|
|
|
case statusCode:
|
|
|
|
// this should not happen, but no need to panic; just ignore this message.
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Warn("unxepected status message received", "peer", p.peer.ID())
|
2016-10-29 07:11:37 -05:00
|
|
|
case messagesCode:
|
|
|
|
// decode the contained envelopes
|
2017-04-26 14:05:48 -05:00
|
|
|
var envelope Envelope
|
|
|
|
if err := packet.Decode(&envelope); err != nil {
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Warn("failed to decode envelope, peer will be disconnected", "peer", p.peer.ID(), "err", err)
|
|
|
|
return errors.New("invalid envelope")
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2018-05-02 01:17:17 -05:00
|
|
|
cached, err := w.add(&envelope)
|
2017-04-26 14:05:48 -05:00
|
|
|
if err != nil {
|
|
|
|
log.Warn("bad envelope received, peer will be disconnected", "peer", p.peer.ID(), "err", err)
|
|
|
|
return errors.New("invalid envelope")
|
|
|
|
}
|
|
|
|
if cached {
|
|
|
|
p.mark(&envelope)
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
case p2pCode:
|
|
|
|
// 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 {
|
2017-01-31 04:16:20 -06:00
|
|
|
var envelope Envelope
|
|
|
|
if err := packet.Decode(&envelope); err != nil {
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Warn("failed to decode direct message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
|
|
|
|
return errors.New("invalid direct message")
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2018-05-02 01:17:17 -05:00
|
|
|
w.postEvent(&envelope, true)
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2016-12-19 17:58:01 -06:00
|
|
|
case p2pRequestCode:
|
2016-10-29 07:11:37 -05:00
|
|
|
// Must be processed if mail server is implemented. Otherwise ignore.
|
2018-05-02 01:17:17 -05:00
|
|
|
if w.mailServer != nil {
|
2017-01-31 04:16:20 -06:00
|
|
|
var request Envelope
|
|
|
|
if err := packet.Decode(&request); err != nil {
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Warn("failed to decode p2p request message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
|
|
|
|
return errors.New("invalid p2p request")
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2018-05-02 01:17:17 -05:00
|
|
|
w.mailServer.DeliverMail(p, &request)
|
2016-10-29 07:11:37 -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-05-02 01:17:17 -05:00
|
|
|
func (w *Whisper) add(envelope *Envelope) (bool, error) {
|
2016-10-29 07:11:37 -05:00
|
|
|
now := uint32(time.Now().Unix())
|
|
|
|
sent := envelope.Expiry - envelope.TTL
|
|
|
|
|
|
|
|
if sent > now {
|
|
|
|
if sent-SynchAllowance > now {
|
2017-02-23 11:46:32 -06:00
|
|
|
return false, fmt.Errorf("envelope created in the future [%x]", envelope.Hash())
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2018-05-02 01:17:17 -05:00
|
|
|
// recalculate PoW, adjusted for the time difference, plus one second for latency
|
|
|
|
envelope.calculatePoW(sent - now + 1)
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
if envelope.Expiry < now {
|
|
|
|
if envelope.Expiry+SynchAllowance*2 < now {
|
2017-02-23 11:46:32 -06:00
|
|
|
return false, fmt.Errorf("very old message")
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2018-05-02 01:17:17 -05:00
|
|
|
log.Debug("expired envelope dropped", "hash", envelope.Hash().Hex())
|
|
|
|
return false, nil // drop envelope without error
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2018-05-02 01:17:17 -05:00
|
|
|
if uint32(envelope.size()) > w.MaxMessageSize() {
|
2017-02-23 11:46:32 -06:00
|
|
|
return false, fmt.Errorf("huge messages are not allowed [%x]", envelope.Hash())
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
if len(envelope.Version) > 4 {
|
2017-02-23 11:46:32 -06:00
|
|
|
return false, fmt.Errorf("oversized version [%x]", envelope.Hash())
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2017-04-26 14:05:48 -05:00
|
|
|
aesNonceSize := len(envelope.AESNonce)
|
|
|
|
if aesNonceSize != 0 && aesNonceSize != AESNonceLength {
|
|
|
|
// the standard AES GCM nonce size is 12 bytes,
|
|
|
|
// but constant gcmStandardNonceSize cannot be accessed (not exported)
|
|
|
|
return false, fmt.Errorf("wrong size of AESNonce: %d bytes [env: %x]", aesNonceSize, envelope.Hash())
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2018-05-02 01:17:17 -05:00
|
|
|
if envelope.PoW() < w.MinPow() {
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Debug("envelope with low PoW dropped", "PoW", envelope.PoW(), "hash", envelope.Hash().Hex())
|
2017-02-23 11:46:32 -06:00
|
|
|
return false, nil // drop envelope without error
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
hash := envelope.Hash()
|
|
|
|
|
2018-05-02 01:17:17 -05:00
|
|
|
w.poolMu.Lock()
|
|
|
|
_, alreadyCached := w.envelopes[hash]
|
2016-10-29 07:11:37 -05:00
|
|
|
if !alreadyCached {
|
2018-05-02 01:17:17 -05:00
|
|
|
w.envelopes[hash] = envelope
|
|
|
|
if w.expirations[envelope.Expiry] == nil {
|
|
|
|
w.expirations[envelope.Expiry] = set.NewNonTS()
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2018-05-02 01:17:17 -05:00
|
|
|
if !w.expirations[envelope.Expiry].Has(hash) {
|
|
|
|
w.expirations[envelope.Expiry].Add(hash)
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
}
|
2018-05-02 01:17:17 -05:00
|
|
|
w.poolMu.Unlock()
|
2016-10-29 07:11:37 -05:00
|
|
|
|
|
|
|
if alreadyCached {
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Trace("whisper envelope already cached", "hash", envelope.Hash().Hex())
|
2016-10-29 07:11:37 -05:00
|
|
|
} else {
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Trace("cached whisper envelope", "hash", envelope.Hash().Hex())
|
2018-05-02 01:17:17 -05:00
|
|
|
w.statsMu.Lock()
|
|
|
|
w.stats.memoryUsed += envelope.size()
|
|
|
|
w.statsMu.Unlock()
|
|
|
|
w.postEvent(envelope, false) // notify the local node about the new message
|
|
|
|
if w.mailServer != nil {
|
|
|
|
w.mailServer.Archive(envelope)
|
2017-01-31 04:16:20 -06:00
|
|
|
}
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2017-02-23 11:46:32 -06:00
|
|
|
return true, nil
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
|
2016-12-19 17:58:01 -06:00
|
|
|
// postEvent queues the message for further processing.
|
|
|
|
func (w *Whisper) postEvent(envelope *Envelope, isP2P bool) {
|
2016-10-29 07:11:37 -05:00
|
|
|
// if the version of incoming message is higher than
|
|
|
|
// currently supported version, we can not decrypt it,
|
|
|
|
// and therefore just ignore this message
|
|
|
|
if envelope.Ver() <= EnvelopeVersion {
|
2016-12-19 17:58:01 -06:00
|
|
|
if isP2P {
|
|
|
|
w.p2pMsgQueue <- envelope
|
|
|
|
} else {
|
|
|
|
w.checkOverflow()
|
|
|
|
w.messageQueue <- envelope
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// checkOverflow checks if message queue overflow occurs and reports it if necessary.
|
|
|
|
func (w *Whisper) checkOverflow() {
|
|
|
|
queueSize := len(w.messageQueue)
|
|
|
|
|
|
|
|
if queueSize == messageQueueLimit {
|
2017-06-13 04:49:07 -05:00
|
|
|
if !w.Overflow() {
|
2017-06-21 04:15:47 -05:00
|
|
|
w.settings.Store(overflowIdx, true)
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Warn("message queue overflow")
|
2016-12-19 17:58:01 -06:00
|
|
|
}
|
|
|
|
} else if queueSize <= messageQueueLimit/2 {
|
2017-06-13 04:49:07 -05:00
|
|
|
if w.Overflow() {
|
2017-06-21 04:15:47 -05:00
|
|
|
w.settings.Store(overflowIdx, false)
|
2017-04-09 16:49:22 -05:00
|
|
|
log.Warn("message queue overflow fixed (back to normal)")
|
2016-12-19 17:58:01 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// processQueue delivers the messages to the watchers during the lifetime of the whisper node.
|
|
|
|
func (w *Whisper) processQueue() {
|
|
|
|
var e *Envelope
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-w.quit:
|
|
|
|
return
|
|
|
|
|
|
|
|
case e = <-w.messageQueue:
|
|
|
|
w.filters.NotifyWatchers(e, false)
|
|
|
|
|
|
|
|
case e = <-w.p2pMsgQueue:
|
|
|
|
w.filters.NotifyWatchers(e, true)
|
|
|
|
}
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// update loops until the lifetime of the whisper node, updating its internal
|
|
|
|
// state by expiring stale messages from the pool.
|
|
|
|
func (w *Whisper) update() {
|
|
|
|
// Start a ticker to check for expirations
|
|
|
|
expire := time.NewTicker(expirationCycle)
|
|
|
|
|
|
|
|
// Repeat updates until termination is requested
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-expire.C:
|
|
|
|
w.expire()
|
|
|
|
|
|
|
|
case <-w.quit:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// expire iterates over all the expiration timestamps, removing all stale
|
|
|
|
// messages from the pools.
|
|
|
|
func (w *Whisper) expire() {
|
|
|
|
w.poolMu.Lock()
|
|
|
|
defer w.poolMu.Unlock()
|
|
|
|
|
2017-06-13 04:49:07 -05:00
|
|
|
w.statsMu.Lock()
|
|
|
|
defer w.statsMu.Unlock()
|
2017-04-09 16:49:22 -05:00
|
|
|
w.stats.reset()
|
2016-10-29 07:11:37 -05:00
|
|
|
now := uint32(time.Now().Unix())
|
2017-02-23 11:46:32 -06:00
|
|
|
for expiry, hashSet := range w.expirations {
|
|
|
|
if expiry < now {
|
|
|
|
// Dump all expired messages and remove timestamp
|
|
|
|
hashSet.Each(func(v interface{}) bool {
|
|
|
|
sz := w.envelopes[v.(common.Hash)].size()
|
|
|
|
delete(w.envelopes, v.(common.Hash))
|
2017-04-09 16:49:22 -05:00
|
|
|
w.stats.messagesCleared++
|
|
|
|
w.stats.memoryCleared += sz
|
|
|
|
w.stats.memoryUsed -= sz
|
2017-02-23 11:46:32 -06:00
|
|
|
return true
|
|
|
|
})
|
|
|
|
w.expirations[expiry].Clear()
|
|
|
|
delete(w.expirations, expiry)
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// Stats returns the whisper node statistics.
|
2017-06-13 04:49:07 -05:00
|
|
|
func (w *Whisper) Stats() Statistics {
|
|
|
|
w.statsMu.Lock()
|
|
|
|
defer w.statsMu.Unlock()
|
|
|
|
|
|
|
|
return w.stats
|
2017-02-23 11:46:32 -06:00
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// Envelopes retrieves all the messages currently pooled by the node.
|
2016-10-29 07:11:37 -05:00
|
|
|
func (w *Whisper) Envelopes() []*Envelope {
|
|
|
|
w.poolMu.RLock()
|
|
|
|
defer w.poolMu.RUnlock()
|
|
|
|
|
|
|
|
all := make([]*Envelope, 0, len(w.envelopes))
|
|
|
|
for _, envelope := range w.envelopes {
|
|
|
|
all = append(all, envelope)
|
|
|
|
}
|
|
|
|
return all
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// Messages iterates through all currently floating envelopes
|
|
|
|
// and retrieves all the messages, that this filter could decrypt.
|
2017-02-23 02:41:47 -06:00
|
|
|
func (w *Whisper) Messages(id string) []*ReceivedMessage {
|
2016-10-29 07:11:37 -05:00
|
|
|
result := make([]*ReceivedMessage, 0)
|
|
|
|
w.poolMu.RLock()
|
|
|
|
defer w.poolMu.RUnlock()
|
|
|
|
|
|
|
|
if filter := w.filters.Get(id); filter != nil {
|
2017-04-09 16:49:22 -05:00
|
|
|
for _, env := range w.envelopes {
|
|
|
|
msg := filter.processEnvelope(env)
|
|
|
|
if msg != nil {
|
2016-10-29 07:11:37 -05:00
|
|
|
result = append(result, msg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// isEnvelopeCached checks if envelope with specific hash has already been received and cached.
|
2017-02-23 11:46:32 -06:00
|
|
|
func (w *Whisper) isEnvelopeCached(hash common.Hash) bool {
|
|
|
|
w.poolMu.Lock()
|
|
|
|
defer w.poolMu.Unlock()
|
|
|
|
|
|
|
|
_, exist := w.envelopes[hash]
|
|
|
|
return exist
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// reset resets the node's statistics after each expiry cycle.
|
|
|
|
func (s *Statistics) reset() {
|
|
|
|
s.cycles++
|
|
|
|
s.totalMessagesCleared += s.messagesCleared
|
2016-10-29 07:11:37 -05:00
|
|
|
|
2017-02-23 11:46:32 -06:00
|
|
|
s.memoryCleared = 0
|
|
|
|
s.messagesCleared = 0
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// ValidatePublicKey checks the format of the given public key.
|
2016-10-29 07:11:37 -05:00
|
|
|
func ValidatePublicKey(k *ecdsa.PublicKey) bool {
|
|
|
|
return k != nil && k.X != nil && k.Y != nil && k.X.Sign() != 0 && k.Y.Sign() != 0
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// validatePrivateKey checks the format of the given private key.
|
2016-10-29 07:11:37 -05:00
|
|
|
func validatePrivateKey(k *ecdsa.PrivateKey) bool {
|
|
|
|
if k == nil || k.D == nil || k.D.Sign() == 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return ValidatePublicKey(&k.PublicKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
// validateSymmetricKey returns false if the key contains all zeros
|
|
|
|
func validateSymmetricKey(k []byte) bool {
|
|
|
|
return len(k) > 0 && !containsOnlyZeros(k)
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// containsOnlyZeros checks if the data contain only zeros.
|
2016-10-29 07:11:37 -05:00
|
|
|
func containsOnlyZeros(data []byte) bool {
|
|
|
|
for _, b := range data {
|
|
|
|
if b != 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// bytesToUintLittleEndian converts the slice to 64-bit unsigned integer.
|
|
|
|
func bytesToUintLittleEndian(b []byte) (res uint64) {
|
2016-10-29 07:11:37 -05:00
|
|
|
mul := uint64(1)
|
|
|
|
for i := 0; i < len(b); i++ {
|
|
|
|
res += uint64(b[i]) * mul
|
|
|
|
mul *= 256
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// BytesToUintBigEndian converts the slice to 64-bit unsigned integer.
|
|
|
|
func BytesToUintBigEndian(b []byte) (res uint64) {
|
2016-10-29 07:11:37 -05:00
|
|
|
for i := 0; i < len(b); i++ {
|
|
|
|
res *= 256
|
|
|
|
res += uint64(b[i])
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
2017-04-09 16:49:22 -05:00
|
|
|
// deriveKeyMaterial derives symmetric key material from the key or password.
|
2016-10-29 07:11:37 -05:00
|
|
|
// pbkdf2 is used for security, in case people use password instead of randomly generated keys.
|
|
|
|
func deriveKeyMaterial(key []byte, version uint64) (derivedKey []byte, err error) {
|
|
|
|
if version == 0 {
|
|
|
|
// kdf should run no less than 0.1 seconds on average compute,
|
|
|
|
// because it's a once in a session experience
|
|
|
|
derivedKey := pbkdf2.Key(key, nil, 65356, aesKeyLength, sha256.New)
|
|
|
|
return derivedKey, nil
|
|
|
|
}
|
2018-05-02 01:17:17 -05:00
|
|
|
return nil, unknownVersionError(version)
|
2016-10-29 07:11:37 -05:00
|
|
|
}
|
2017-04-09 16:49:22 -05:00
|
|
|
|
|
|
|
// GenerateRandomID generates a random string, which is then returned to be used as a key id
|
|
|
|
func GenerateRandomID() (id string, err error) {
|
|
|
|
buf := make([]byte, keyIdSize)
|
|
|
|
_, err = crand.Read(buf)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if !validateSymmetricKey(buf) {
|
|
|
|
return "", fmt.Errorf("error in generateRandomID: crypto/rand failed to generate random data")
|
|
|
|
}
|
|
|
|
id = common.Bytes2Hex(buf)
|
|
|
|
return id, err
|
|
|
|
}
|