whisper: fixed PR according to request of @fjl

This commit is contained in:
Vlad 2016-09-23 16:38:33 +02:00
parent c7c7239ef7
commit 18ff2ad5f4
25 changed files with 250 additions and 261 deletions

View file

@ -32,7 +32,7 @@ import (
"github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/tests" "github.com/ethereum/go-ethereum/tests"
whisper "github.com/ethereum/go-ethereum/whisper/whisper02" whisper "github.com/ethereum/go-ethereum/whisper/whisperv2"
) )
const defaultTestKey = "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291" const defaultTestKey = "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291"

View file

@ -48,7 +48,7 @@ import (
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/pow" "github.com/ethereum/go-ethereum/pow"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
whisper "github.com/ethereum/go-ethereum/whisper/whisper02" whisper "github.com/ethereum/go-ethereum/whisper/whisperv2"
"gopkg.in/urfave/cli.v1" "gopkg.in/urfave/cli.v1"
) )

View file

@ -14,32 +14,53 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper05 package shhapi
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
mathrand "math/rand"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog" "github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/ethereum/go-ethereum/whisper/whisperv5"
mathrand "math/rand"
) )
type WhisperOfflineError struct{}
var whisperOffLineErr = new(WhisperOfflineError)
func (e *WhisperOfflineError) Error() string {
return "whisper is offline"
}
// PublicWhisperAPI provides the whisper RPC service. // PublicWhisperAPI provides the whisper RPC service.
type PublicWhisperAPI struct { type PublicWhisperAPI struct {
whisper *Whisper whisper *whisperv5.Whisper
} }
// NewPublicWhisperAPI create a new RPC whisper service. // NewPublicWhisperAPI create a new RPC whisper service.
func NewPublicWhisperAPI(w *Whisper) *PublicWhisperAPI { func NewPublicWhisperAPI() *PublicWhisperAPI {
w := whisperv5.New(nil)
return &PublicWhisperAPI{whisper: w} return &PublicWhisperAPI{whisper: w}
} }
// APIs returns the RPC descriptors the Whisper implementation offers
func APIs() []rpc.API {
return []rpc.API{
{
Namespace: whisperv5.ProtocolName,
Version: whisperv5.ProtocolVersionStr,
Service: NewPublicWhisperAPI(),
Public: true,
},
}
}
// Version returns the Whisper version this node offers. // Version returns the Whisper version this node offers.
func (self *PublicWhisperAPI) Version() (*rpc.HexNumber, error) { func (self *PublicWhisperAPI) Version() (*rpc.HexNumber, error) {
if self.whisper == nil { if self.whisper == nil {
@ -54,7 +75,7 @@ func (self *PublicWhisperAPI) MarkPeerTrusted(peerID *rpc.HexBytes) error {
if self.whisper == nil { if self.whisper == nil {
return whisperOffLineErr return whisperOffLineErr
} }
return self.whisper.MarkPeerTrusted(peerID) return self.whisper.MarkPeerTrusted(*peerID)
} }
// RequestHistoricMessages requests the peer to deliver the old (expired) messages. // RequestHistoricMessages requests the peer to deliver the old (expired) messages.
@ -65,7 +86,7 @@ func (self *PublicWhisperAPI) RequestHistoricMessages(peerID *rpc.HexBytes, data
if self.whisper == nil { if self.whisper == nil {
return whisperOffLineErr return whisperOffLineErr
} }
return self.whisper.RequestHistoricMessages(peerID, data) return self.whisper.RequestHistoricMessages(*peerID, *data)
} }
// HasIdentity checks if the the whisper node is configured with the private key // HasIdentity checks if the the whisper node is configured with the private key
@ -134,13 +155,13 @@ func (self *PublicWhisperAPI) NewFilter(args WhisperFilterArgs) (*rpc.HexNumber,
return nil, whisperOffLineErr return nil, whisperOffLineErr
} }
filter := Filter{ filter := whisperv5.Filter{
Src: crypto.ToECDSAPub(args.From), Src: crypto.ToECDSAPub(args.From),
Dst: crypto.ToECDSAPub(args.To), Dst: crypto.ToECDSAPub(args.To),
KeySym: self.whisper.GetTopicKey(args.KeyName), KeySym: self.whisper.GetTopicKey(args.KeyName),
PoW: args.PoW, PoW: args.PoW,
messages: make(map[common.Hash]*ReceivedMessage), Messages: make(map[common.Hash]*whisperv5.ReceivedMessage),
acceptP2P: args.AcceptP2P, AcceptP2P: args.AcceptP2P,
} }
if len(filter.KeySym) > 0 { if len(filter.KeySym) > 0 {
@ -176,7 +197,7 @@ func (self *PublicWhisperAPI) NewFilter(args WhisperFilterArgs) (*rpc.HexNumber,
} }
if len(args.To) > 0 { if len(args.To) > 0 {
if !validatePublicKey(filter.Dst) { if !whisperv5.ValidatePublicKey(filter.Dst) {
info := "NewFilter: Invalid 'To' address" info := "NewFilter: Invalid 'To' address"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return nil, errors.New(info) return nil, errors.New(info)
@ -190,7 +211,7 @@ func (self *PublicWhisperAPI) NewFilter(args WhisperFilterArgs) (*rpc.HexNumber,
} }
if len(args.From) > 0 { if len(args.From) > 0 {
if !validatePublicKey(filter.Src) { if !whisperv5.ValidatePublicKey(filter.Src) {
info := "NewFilter: Invalid 'From' address" info := "NewFilter: Invalid 'From' address"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return nil, errors.New(info) return nil, errors.New(info)
@ -208,9 +229,9 @@ func (self *PublicWhisperAPI) UninstallFilter(filterId rpc.HexNumber) {
// GetFilterChanges retrieves all the new messages matched by a filter since the last retrieval. // GetFilterChanges retrieves all the new messages matched by a filter since the last retrieval.
func (self *PublicWhisperAPI) GetFilterChanges(filterId rpc.HexNumber) []WhisperMessage { func (self *PublicWhisperAPI) GetFilterChanges(filterId rpc.HexNumber) []WhisperMessage {
f := self.whisper.filters.Get(filterId.Int()) f := self.whisper.GetFilter(filterId.Int())
if f != nil { if f != nil {
newMail := f.retrieve() newMail := f.Retrieve()
return toWhisperMessages(newMail) return toWhisperMessages(newMail)
} }
return toWhisperMessages(nil) return toWhisperMessages(nil)
@ -223,7 +244,7 @@ func (self *PublicWhisperAPI) GetMessages(filterId rpc.HexNumber) []WhisperMessa
} }
// toWhisperMessages converts a Whisper message to a RPC whisper message. // toWhisperMessages converts a Whisper message to a RPC whisper message.
func toWhisperMessages(messages []*ReceivedMessage) []WhisperMessage { func toWhisperMessages(messages []*whisperv5.ReceivedMessage) []WhisperMessage {
msgs := make([]WhisperMessage, len(messages)) msgs := make([]WhisperMessage, len(messages))
for i, msg := range messages { for i, msg := range messages {
msgs[i] = NewWhisperMessage(msg) msgs[i] = NewWhisperMessage(msg)
@ -237,7 +258,7 @@ func (self *PublicWhisperAPI) Post(args PostArgs) error {
return whisperOffLineErr return whisperOffLineErr
} }
params := MessageParams{ params := whisperv5.MessageParams{
TTL: args.TTL, TTL: args.TTL,
Dst: crypto.ToECDSAPub(args.To), Dst: crypto.ToECDSAPub(args.To),
KeySym: self.whisper.GetTopicKey(args.KeyName), KeySym: self.whisper.GetTopicKey(args.KeyName),
@ -250,7 +271,7 @@ func (self *PublicWhisperAPI) Post(args PostArgs) error {
if len(args.From) > 0 { if len(args.From) > 0 {
pub := crypto.ToECDSAPub(args.From) pub := crypto.ToECDSAPub(args.From)
if !validatePublicKey(pub) { if !whisperv5.ValidatePublicKey(pub) {
info := "Post: Invalid 'From' address" info := "Post: Invalid 'From' address"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return errors.New(info) return errors.New(info)
@ -263,7 +284,7 @@ func (self *PublicWhisperAPI) Post(args PostArgs) error {
} }
} }
filter := self.whisper.filters.Get(args.FilterID) filter := self.whisper.GetFilter(args.FilterID)
if filter == nil && args.FilterID > -1 { if filter == nil && args.FilterID > -1 {
info := fmt.Sprintf("Post: wrong filter id %d", args.FilterID) info := fmt.Sprintf("Post: wrong filter id %d", args.FilterID)
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
@ -281,7 +302,7 @@ func (self *PublicWhisperAPI) Post(args PostArgs) error {
if params.Src == nil && filter.Src != nil { if params.Src == nil && filter.Src != nil {
params.Src = filter.KeyAsym params.Src = filter.KeyAsym
} }
if (params.Topic == TopicType{}) { if (params.Topic == whisperv5.TopicType{}) {
sz := len(filter.Topics) sz := len(filter.Topics)
if sz < 1 { if sz < 1 {
info := fmt.Sprintf("Post: no topics in filter # %d", args.FilterID) info := fmt.Sprintf("Post: no topics in filter # %d", args.FilterID)
@ -317,7 +338,7 @@ func (self *PublicWhisperAPI) Post(args PostArgs) error {
} }
if len(args.To) > 0 { if len(args.To) > 0 {
if !validatePublicKey(params.Dst) { if !whisperv5.ValidatePublicKey(params.Dst) {
info := "Post: Invalid 'To' address" info := "Post: Invalid 'To' address"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return errors.New(info) return errors.New(info)
@ -325,25 +346,25 @@ func (self *PublicWhisperAPI) Post(args PostArgs) error {
} }
// encrypt and send // encrypt and send
message := NewSentMessage(&params) message := whisperv5.NewSentMessage(&params)
envelope, err := message.Wrap(params) envelope, err := message.Wrap(params)
if err != nil { if err != nil {
glog.V(logger.Error).Infof(err.Error()) glog.V(logger.Error).Infof(err.Error())
return err return err
} }
if len(envelope.Data) > msgMaxLength { if len(envelope.Data) > whisperv5.MaxMessageLength {
info := "Post: message is too big" info := "Post: message is too big"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return errors.New(info) return errors.New(info)
} }
if (envelope.Topic == TopicType{} && envelope.isSymmetric()) { if (envelope.Topic == whisperv5.TopicType{} && envelope.IsSymmetric()) {
info := "Post: topic is missing for symmetric encryption" info := "Post: topic is missing for symmetric encryption"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return errors.New(info) return errors.New(info)
} }
if args.Peer != nil { if args.PeerID != nil {
return self.whisper.SendP2PMessage(&args.Peer, envelope) return self.whisper.SendP2PMessage(args.PeerID, envelope)
} }
return self.whisper.Send(envelope) return self.whisper.Send(envelope)
@ -354,13 +375,13 @@ type PostArgs struct {
From rpc.HexBytes `json:"from"` From rpc.HexBytes `json:"from"`
To rpc.HexBytes `json:"to"` To rpc.HexBytes `json:"to"`
KeyName string `json:"keyname"` KeyName string `json:"keyname"`
Topic TopicType `json:"topic"` Topic whisperv5.TopicType `json:"topic"`
Padding rpc.HexBytes `json:"padding"` Padding rpc.HexBytes `json:"padding"`
Payload rpc.HexBytes `json:"payload"` Payload rpc.HexBytes `json:"payload"`
WorkTime uint32 `json:"worktime"` WorkTime uint32 `json:"worktime"`
PoW float64 `json:"pow"` PoW float64 `json:"pow"`
FilterID int `json:"filter"` FilterID int `json:"filter"`
Peer rpc.HexBytes `json:"directP2P"` PeerID rpc.HexBytes `json:"directP2P"`
} }
func (args *PostArgs) UnmarshalJSON(data []byte) (err error) { func (args *PostArgs) UnmarshalJSON(data []byte) (err error) {
@ -369,13 +390,13 @@ func (args *PostArgs) UnmarshalJSON(data []byte) (err error) {
From rpc.HexBytes `json:"from"` From rpc.HexBytes `json:"from"`
To rpc.HexBytes `json:"to"` To rpc.HexBytes `json:"to"`
KeyName string `json:"keyname"` KeyName string `json:"keyname"`
Topic TopicType `json:"topic"` Topic whisperv5.TopicType `json:"topic"`
Payload rpc.HexBytes `json:"payload"` Payload rpc.HexBytes `json:"payload"`
Padding rpc.HexBytes `json:"padding"` Padding rpc.HexBytes `json:"padding"`
WorkTime uint32 `json:"worktime"` WorkTime uint32 `json:"worktime"`
PoW float64 `json:"pow"` PoW float64 `json:"pow"`
FilterID rpc.HexBytes `json:"filter"` FilterID rpc.HexBytes `json:"filter"`
Peer rpc.HexBytes `json:"directP2P"` PeerID rpc.HexBytes `json:"directP2P"`
} }
if err := json.Unmarshal(data, &obj); err != nil { if err := json.Unmarshal(data, &obj); err != nil {
@ -392,10 +413,10 @@ func (args *PostArgs) UnmarshalJSON(data []byte) (err error) {
args.WorkTime = obj.WorkTime args.WorkTime = obj.WorkTime
args.PoW = obj.PoW args.PoW = obj.PoW
args.FilterID = -1 args.FilterID = -1
args.Peer = obj.Peer args.PeerID = obj.PeerID
if obj.FilterID != nil { if obj.FilterID != nil {
x := bytesToIntBigEndian(obj.FilterID) x := whisperv5.BytesToIntBigEndian(obj.FilterID)
args.FilterID = int(x) args.FilterID = int(x)
} }
@ -407,7 +428,7 @@ type WhisperFilterArgs struct {
From []byte From []byte
KeyName string KeyName string
PoW float64 PoW float64
Topics []TopicType Topics []whisperv5.TopicType
AcceptP2P bool AcceptP2P bool
} }
@ -446,13 +467,13 @@ func (args *WhisperFilterArgs) UnmarshalJSON(b []byte) (err error) {
return fmt.Errorf("topic[%d] is not a string", i) return fmt.Errorf("topic[%d] is not a string", i)
} }
} }
topicsDecoded := make([]TopicType, len(topics)) topicsDecoded := make([]whisperv5.TopicType, len(topics))
for j, s := range topics { for j, s := range topics {
x := common.FromHex(s) x := common.FromHex(s)
if x == nil || len(x) != topicLength { if x == nil || len(x) != whisperv5.TopicLength {
return fmt.Errorf("topic[%d] is invalid", j) return fmt.Errorf("topic[%d] is invalid", j)
} }
topicsDecoded[j] = BytesToTopic(x) topicsDecoded[j] = whisperv5.BytesToTopic(x)
} }
args.Topics = topicsDecoded args.Topics = topicsDecoded
} }
@ -473,7 +494,7 @@ type WhisperMessage struct {
} }
// NewWhisperMessage converts an internal message into an API version. // NewWhisperMessage converts an internal message into an API version.
func NewWhisperMessage(message *ReceivedMessage) WhisperMessage { func NewWhisperMessage(message *whisperv5.ReceivedMessage) WhisperMessage {
return WhisperMessage{ return WhisperMessage{
Payload: common.ToHex(message.Payload), Payload: common.ToHex(message.Payload),
Padding: common.ToHex(message.Padding), Padding: common.ToHex(message.Padding),

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper02 package whisperv2
import ( import (
"encoding/json" "encoding/json"

View file

@ -29,4 +29,4 @@ Whisper is a pure identity-based messaging system. Whisper provides a low-level
or prejudiced by the low-level hardware attributes and characteristics, or prejudiced by the low-level hardware attributes and characteristics,
particularly the notion of singular endpoints. particularly the notion of singular endpoints.
*/ */
package whisper02 package whisperv2

View file

@ -17,7 +17,7 @@
// Contains the Whisper protocol Envelope element. For formal details please see // Contains the Whisper protocol Envelope element. For formal details please see
// the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#envelopes. // the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#envelopes.
package whisper02 package whisperv2
import ( import (
"crypto/ecdsa" "crypto/ecdsa"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper02 package whisperv2
import ( import (
"bytes" "bytes"

View file

@ -16,7 +16,7 @@
// Contains the message filter for fine grained subscriptions. // Contains the message filter for fine grained subscriptions.
package whisper02 package whisperv2
import ( import (
"crypto/ecdsa" "crypto/ecdsa"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper02 package whisperv2
import ( import (
"bytes" "bytes"

View file

@ -17,7 +17,7 @@
// Contains the Whisper protocol Message element. For formal details please see // Contains the Whisper protocol Message element. For formal details please see
// the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#messages. // the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#messages.
package whisper02 package whisperv2
import ( import (
"crypto/ecdsa" "crypto/ecdsa"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper02 package whisperv2
import ( import (
"bytes" "bytes"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper02 package whisperv2
import ( import (
"fmt" "fmt"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper02 package whisperv2
import ( import (
"testing" "testing"

View file

@ -17,7 +17,7 @@
// Contains the Whisper protocol Topic element. For formal details please see // Contains the Whisper protocol Topic element. For formal details please see
// the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#topics. // the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#topics.
package whisper02 package whisperv2
import "github.com/ethereum/go-ethereum/crypto" import "github.com/ethereum/go-ethereum/crypto"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper02 package whisperv2
import ( import (
"bytes" "bytes"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper02 package whisperv2
import ( import (
"crypto/ecdsa" "crypto/ecdsa"

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper02 package whisperv2
import ( import (
"testing" "testing"

View file

@ -29,31 +29,35 @@ Whisper is a pure identity-based messaging system. Whisper provides a low-level
or prejudiced by the low-level hardware attributes and characteristics, or prejudiced by the low-level hardware attributes and characteristics,
particularly the notion of singular endpoints. particularly the notion of singular endpoints.
*/ */
package whisper05 package whisperv5
import ( import (
"fmt"
"time" "time"
) )
const ( const (
EnvelopeVersion = uint64(0) EnvelopeVersion = uint64(0)
protocolVersion = uint64(5) ProtocolVersion = uint64(5)
protocolVersionStr = "5.0" ProtocolVersionStr = "5.0"
protocolName = "shh" ProtocolName = "shh"
statusCode = 0 statusCode = 0
messagesCode = 1 messagesCode = 1
p2pCode = 2 p2pCode = 2
mailRequestCode = 3 mailRequestCode = 3
NumberOfMessageCodes = 4
paddingMask = byte(3) paddingMask = byte(3)
signatureFlag = byte(4) signatureFlag = byte(4)
topicLength = 4 TopicLength = 4
signatureLength = 65 signatureLength = 65
aesKeyLength = 32 aesKeyLength = 32
saltLength = 12 saltLength = 12
msgMaxLength = 0xFFFF
MaxMessageLength = 0xFFFF // todo: remove this restriction after testing in morden and analizing stats. this should be regulated by MinimumPoW.
MinimumPoW = 50.0 // todo: review
padSizeLimitLower = 128 // it can not be less - we don't want to reveal the absence of signature padSizeLimitLower = 128 // it can not be less - we don't want to reveal the absence of signature
padSizeLimitUpper = 256 // just an arbitrary number, could be changed without losing compatibility padSizeLimitUpper = 256 // just an arbitrary number, could be changed without losing compatibility
@ -63,16 +67,12 @@ const (
DefaultTTL = 50 // seconds DefaultTTL = 50 // seconds
SynchAllowance = 10 // seconds SynchAllowance = 10 // seconds
MinimumPoW = 50.0 // todo: review
) )
type whisperOfflineError struct{} type unknownVersionError uint64
var whisperOffLineErr = new(whisperOfflineError) func (e unknownVersionError) Error() string {
return fmt.Sprintf("invalid envelope version %d", uint64(e))
func (e *whisperOfflineError) Error() string {
return "whisper is offline"
} }
// MailServer represents a mail server, capable of // MailServer represents a mail server, capable of
@ -83,5 +83,5 @@ func (e *whisperOfflineError) Error() string {
// in order to bypass the expiry checks. // in order to bypass the expiry checks.
type MailServer interface { type MailServer interface {
Archive(env *Envelope) Archive(env *Envelope)
DeliverMail(whisperPeer *WhisperPeer, data []byte) DeliverMail(whisperPeer *Peer, data []byte)
} }

View file

@ -17,7 +17,7 @@
// Contains the Whisper protocol Envelope element. For formal details please see // Contains the Whisper protocol Envelope element. For formal details please see
// the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#envelopes. // the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#envelopes.
package whisper05 package whisperv5
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
@ -62,20 +62,21 @@ func NewEnvelope(ttl uint32, topic TopicType, salt []byte, aesNonce []byte, msg
EnvNonce: 0, EnvNonce: 0,
} }
if EnvelopeVersion > 255 { if EnvelopeVersion < 256 {
panic("please fix Envelope.Version size before releasing this version") env.Version[0] = byte(EnvelopeVersion)
} else {
panic("please increase the size of Envelope.Version before releasing this version")
} }
env.Version[0] = byte(EnvelopeVersion)
return &env return &env
} }
func (self *Envelope) isSymmetric() bool { func (self *Envelope) IsSymmetric() bool {
return self.AESNonce != nil return self.AESNonce != nil
} }
func (self *Envelope) isAsymmetric() bool { func (self *Envelope) isAsymmetric() bool {
return !self.isSymmetric() return !self.IsSymmetric()
} }
func (self *Envelope) Ver() uint64 { func (self *Envelope) Ver() uint64 {
@ -194,7 +195,7 @@ func (self *Envelope) OpenSymmetric(key []byte) (msg *ReceivedMessage, err error
if err != nil { if err != nil {
msg = nil msg = nil
} }
return return msg, err
} }
// Open tries to decrypt an envelope, and populates the message fields in case of success. // Open tries to decrypt an envelope, and populates the message fields in case of success.
@ -204,7 +205,7 @@ func (self *Envelope) Open(watcher *Filter) (msg *ReceivedMessage) {
if msg != nil { if msg != nil {
msg.Dst = watcher.Dst msg.Dst = watcher.Dst
} }
} else if self.isSymmetric() { } else if self.IsSymmetric() {
msg, _ = self.OpenSymmetric(watcher.KeySym) msg, _ = self.OpenSymmetric(watcher.KeySym)
if msg != nil { if msg != nil {
msg.TopicKeyHash = crypto.Keccak256Hash(watcher.KeySym) msg.TopicKeyHash = crypto.Keccak256Hash(watcher.KeySym)

View file

@ -14,11 +14,10 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper05 package whisperv5
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"sync" "sync"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
@ -32,10 +31,9 @@ type Filter struct {
KeySym []byte // Key associated with the Topic KeySym []byte // Key associated with the Topic
TopicKeyHash common.Hash // The Keccak256Hash of the symmetric key TopicKeyHash common.Hash // The Keccak256Hash of the symmetric key
PoW float64 // Proof of work as described in the Whisper spec PoW float64 // Proof of work as described in the Whisper spec
acceptP2P bool // Indicates whether this filter is interested in direct peer-to-peer messages AcceptP2P bool // Indicates whether this filter is interested in direct peer-to-peer messages
Messages map[common.Hash]*ReceivedMessage
messages map[common.Hash]*ReceivedMessage Mutex sync.RWMutex
mutex sync.RWMutex
} }
type Filters struct { type Filters struct {
@ -78,7 +76,7 @@ func (self *Filters) NotifyWatchers(env *Envelope, messageCode uint64) {
self.mutex.RLock() self.mutex.RLock()
var msg *ReceivedMessage var msg *ReceivedMessage
for _, watcher := range self.watchers { for _, watcher := range self.watchers {
if messageCode == p2pCode && !watcher.acceptP2P { if messageCode == p2pCode && !watcher.AcceptP2P {
continue continue
} }
@ -112,23 +110,23 @@ func (self *Filter) expectsSymmetricEncryption() bool {
} }
func (self *Filter) Trigger(msg *ReceivedMessage) { func (self *Filter) Trigger(msg *ReceivedMessage) {
self.mutex.Lock() self.Mutex.Lock()
defer self.mutex.Unlock() defer self.Mutex.Unlock()
if _, exist := self.messages[msg.EnvelopeHash]; !exist { if _, exist := self.Messages[msg.EnvelopeHash]; !exist {
self.messages[msg.EnvelopeHash] = msg self.Messages[msg.EnvelopeHash] = msg
} }
} }
func (self *Filter) retrieve() (all []*ReceivedMessage) { func (self *Filter) Retrieve() (all []*ReceivedMessage) {
self.mutex.Lock() self.Mutex.Lock()
defer self.mutex.Unlock() defer self.Mutex.Unlock()
all = make([]*ReceivedMessage, 0, len(self.messages)) all = make([]*ReceivedMessage, 0, len(self.Messages))
for _, msg := range self.messages { for _, msg := range self.Messages {
all = append(all, msg) all = append(all, msg)
} }
self.messages = make(map[common.Hash]*ReceivedMessage) // delete old messages self.Messages = make(map[common.Hash]*ReceivedMessage) // delete old messages
return all return all
} }
@ -169,7 +167,7 @@ func (self *Filter) MatchEnvelope(envelope *Envelope) bool {
if self.Topics == nil { if self.Topics == nil {
return true // wildcard return true // wildcard
} }
} else if self.expectsSymmetricEncryption() && envelope.isSymmetric() { } else if self.expectsSymmetricEncryption() && envelope.IsSymmetric() {
encryptionMethodMatch = true encryptionMethodMatch = true
} }
@ -185,9 +183,9 @@ func (self *Filter) MatchEnvelope(envelope *Envelope) bool {
} }
func isEqual(a, b *ecdsa.PublicKey) bool { func isEqual(a, b *ecdsa.PublicKey) bool {
if !validatePublicKey(a) { if !ValidatePublicKey(a) {
return false return false
} else if !validatePublicKey(b) { } else if !ValidatePublicKey(b) {
return false return false
} }
// the Curve is always the same, just compare the points // the Curve is always the same, just compare the points

View file

@ -18,23 +18,21 @@
// the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#messages. // the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#messages.
// todo: fix the spec link, and move it to doc.go // todo: fix the spec link, and move it to doc.go
package whisper05 package whisperv5
import ( import (
"errors"
"fmt"
"crypto/aes" "crypto/aes"
"crypto/cipher" "crypto/cipher"
"crypto/ecdsa" "crypto/ecdsa"
crand "crypto/rand" crand "crypto/rand"
"crypto/sha256" "crypto/sha256"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog" "github.com/ethereum/go-ethereum/logger/glog"
"golang.org/x/crypto/pbkdf2" "golang.org/x/crypto/pbkdf2"
) )
@ -95,13 +93,13 @@ func (self *ReceivedMessage) isAsymmetricEncryption() bool {
return self.Dst != nil return self.Dst != nil
} }
func DeriveOneTimeKey(key []byte, salt []byte, version uint64) (derivedKey []byte, err error) { func DeriveOneTimeKey(key []byte, salt []byte, version uint64) ([]byte, error) {
if version == 0 { if version == 0 {
derivedKey = pbkdf2.Key(key, salt, 16, aesKeyLength, sha256.New) derivedKey := pbkdf2.Key(key, salt, 16, aesKeyLength, sha256.New)
return derivedKey, nil
} else { } else {
err = fmt.Errorf("DeriveKey: invalid envelope version: %d", version) return nil, unknownVersionError(version)
} }
return
} }
// NewMessage creates and initializes a non-signed, non-encrypted Whisper message. // NewMessage creates and initializes a non-signed, non-encrypted Whisper message.
@ -137,7 +135,7 @@ func (self *SentMessage) appendPadding(params *MessageParams) {
padSize := padChunk - odd padSize := padChunk - odd
if padSize > 255 { if padSize > 255 {
// this algorithm is only valid if padSizeLimitUpper <= 256. // this algorithm is only valid if padSizeLimitUpper <= 256.
// if padSizeLimitUpper will every change, please fix the algorithm // if padSizeLimitUpper will ever change, please fix the algorithm
// (for more information see ReceivedMessage.extractPadding() function). // (for more information see ReceivedMessage.extractPadding() function).
panic("please fix the padding algorithm before releasing new version") panic("please fix the padding algorithm before releasing new version")
} }
@ -154,24 +152,25 @@ func (self *SentMessage) appendPadding(params *MessageParams) {
// sign calculates and sets the cryptographic signature for the message, // sign calculates and sets the cryptographic signature for the message,
// also setting the sign flag. // also setting the sign flag.
func (self *SentMessage) sign(key *ecdsa.PrivateKey) (err error) { func (self *SentMessage) sign(key *ecdsa.PrivateKey) error {
if isMessageSigned(self.Raw[0]) { if isMessageSigned(self.Raw[0]) {
// this should not happen, but no reason to panic // this should not happen, but no reason to panic
glog.V(logger.Error).Infof("Trying to sign a message which was already signed") glog.V(logger.Error).Infof("Trying to sign a message which was already signed")
return return nil
} }
hash := crypto.Keccak256(self.Raw) hash := crypto.Keccak256(self.Raw)
signature, err := crypto.Sign(hash, key) signature, err := crypto.Sign(hash, key)
if err != nil { if err != nil {
self.Raw = append(self.Raw, signature...) self.Raw = append(self.Raw, signature...)
self.Raw[0] |= signatureFlag self.Raw[0] |= signatureFlag
return err
} }
return return nil
} }
// encryptAsymmetric encrypts a message with a public key. // encryptAsymmetric encrypts a message with a public key.
func (self *SentMessage) encryptAsymmetric(key *ecdsa.PublicKey) error { func (self *SentMessage) encryptAsymmetric(key *ecdsa.PublicKey) error {
if !validatePublicKey(key) { if !ValidatePublicKey(key) {
return fmt.Errorf("Invalid public key provided for asymmetric encryption") return fmt.Errorf("Invalid public key provided for asymmetric encryption")
} }
encrypted, err := crypto.Encrypt(key, self.Raw) encrypted, err := crypto.Encrypt(key, self.Raw)
@ -185,44 +184,41 @@ func (self *SentMessage) encryptAsymmetric(key *ecdsa.PublicKey) error {
// nonce size should be 12 bytes (see cipher.gcmStandardNonceSize). // nonce size should be 12 bytes (see cipher.gcmStandardNonceSize).
func (self *SentMessage) encryptSymmetric(key []byte) (salt []byte, nonce []byte, err error) { func (self *SentMessage) encryptSymmetric(key []byte) (salt []byte, nonce []byte, err error) {
if !validateSymmetricKey(key) { if !validateSymmetricKey(key) {
err = fmt.Errorf("encryptSymmetric: invalid key provided for symmetric encryption") return nil, nil, errors.New("invalid key provided for symmetric encryption")
return
} }
salt = make([]byte, saltLength) salt = make([]byte, saltLength)
_, err = crand.Read(salt) _, err = crand.Read(salt)
if err != nil { if err != nil {
return return nil, nil, err
} else if !validateSymmetricKey(salt) { } else if !validateSymmetricKey(salt) {
err = fmt.Errorf("encryptSymmetric: failed to generate salt") return nil, nil, errors.New("crypto/rand failed to generate salt")
return
} }
derivedKey, err := DeriveOneTimeKey(key, salt, EnvelopeVersion) derivedKey, err := DeriveOneTimeKey(key, salt, EnvelopeVersion)
if err != nil { if err != nil {
return return nil, nil, err
} }
if !validateSymmetricKey(derivedKey) { if !validateSymmetricKey(derivedKey) {
err = fmt.Errorf("encryptSymmetric: invalid key derived") return nil, nil, errors.New("failed to derive one-time key")
return
} }
block, err := aes.NewCipher(derivedKey) block, err := aes.NewCipher(derivedKey)
if err != nil { if err != nil {
return return nil, nil, err
} }
aesgcm, err := cipher.NewGCM(block) aesgcm, err := cipher.NewGCM(block)
if err != nil { if err != nil {
return return nil, nil, err
} }
// never use more than 2^32 random nonces with a given key // never use more than 2^32 random nonces with a given key
nonce = make([]byte, aesgcm.NonceSize()) nonce = make([]byte, aesgcm.NonceSize())
_, err = crand.Read(nonce) _, err = crand.Read(nonce)
if err != nil { if err != nil {
return return nil, nil, err
} }
self.Raw = aesgcm.Seal(nil, nonce, self.Raw, nil) self.Raw = aesgcm.Seal(nil, nonce, self.Raw, nil)
return return salt, nonce, nil
} }
// Wrap bundles the message into an Envelope to transmit over the network. // Wrap bundles the message into an Envelope to transmit over the network.
@ -243,13 +239,12 @@ func (self *SentMessage) Wrap(options MessageParams) (envelope *Envelope, err er
} }
if options.Src != nil { if options.Src != nil {
if err = self.sign(options.Src); err != nil { if err = self.sign(options.Src); err != nil {
return return nil, err
} }
} }
if len(self.Raw) > msgMaxLength { if len(self.Raw) > MaxMessageLength {
glog.V(logger.Error).Infof("Message size must not exceed %d bytes", msgMaxLength) glog.V(logger.Error).Infof("Message size must not exceed %d bytes", MaxMessageLength)
err = errors.New("Oversized message") return nil, errors.New("Oversized message")
return
} }
var salt, nonce []byte var salt, nonce []byte
if options.Dst != nil { if options.Dst != nil {
@ -260,11 +255,13 @@ func (self *SentMessage) Wrap(options MessageParams) (envelope *Envelope, err er
err = errors.New("Unable to encrypt the message: neither Dst nor Key") err = errors.New("Unable to encrypt the message: neither Dst nor Key")
} }
if err == nil { if err != nil {
return nil, err
}
envelope = NewEnvelope(options.TTL, options.Topic, salt, nonce, self) envelope = NewEnvelope(options.TTL, options.Topic, salt, nonce, self)
envelope.Seal(options) envelope.Seal(options)
} return envelope, nil
return
} }
// decryptSymmetric decrypts a message with a topic key, using AES-GCM-256. // decryptSymmetric decrypts a message with a topic key, using AES-GCM-256.

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper05 package whisperv5
import ( import (
"fmt" "fmt"
@ -29,7 +29,7 @@ import (
) )
// peer represents a whisper protocol peer connection. // peer represents a whisper protocol peer connection.
type WhisperPeer struct { type Peer struct {
host *Whisper host *Whisper
peer *p2p.Peer peer *p2p.Peer
ws p2p.MsgReadWriter ws p2p.MsgReadWriter
@ -41,8 +41,8 @@ type WhisperPeer struct {
} }
// newPeer creates a new whisper peer object, but does not run the handshake itself. // newPeer creates a new whisper peer object, but does not run the handshake itself.
func newPeer(host *Whisper, remote *p2p.Peer, rw p2p.MsgReadWriter) *WhisperPeer { func newPeer(host *Whisper, remote *p2p.Peer, rw p2p.MsgReadWriter) *Peer {
return &WhisperPeer{ return &Peer{
host: host, host: host,
peer: remote, peer: remote,
ws: rw, ws: rw,
@ -54,24 +54,24 @@ func newPeer(host *Whisper, remote *p2p.Peer, rw p2p.MsgReadWriter) *WhisperPeer
// start initiates the peer updater, periodically broadcasting the whisper packets // start initiates the peer updater, periodically broadcasting the whisper packets
// into the network. // into the network.
func (self *WhisperPeer) start() { func (self *Peer) start() {
go self.update() go self.update()
glog.V(logger.Debug).Infof("%v: whisper started", self.peer) glog.V(logger.Debug).Infof("%v: whisper started", self.peer)
} }
// stop terminates the peer updater, stopping message forwarding to it. // stop terminates the peer updater, stopping message forwarding to it.
func (self *WhisperPeer) stop() { func (self *Peer) stop() {
close(self.quit) close(self.quit)
glog.V(logger.Debug).Infof("%v: whisper stopped", self.peer) glog.V(logger.Debug).Infof("%v: whisper stopped", self.peer)
} }
// handshake sends the protocol initiation status message to the remote peer and // handshake sends the protocol initiation status message to the remote peer and
// verifies the remote status too. // verifies the remote status too.
func (self *WhisperPeer) handshake() error { func (self *Peer) handshake() error {
// Send the handshake status message asynchronously // Send the handshake status message asynchronously
errc := make(chan error, 1) errc := make(chan error, 1)
go func() { go func() {
errc <- p2p.Send(self.ws, statusCode, protocolVersion) errc <- p2p.Send(self.ws, statusCode, ProtocolVersion)
}() }()
// Fetch the remote status packet and verify protocol match // Fetch the remote status packet and verify protocol match
packet, err := self.ws.ReadMsg() packet, err := self.ws.ReadMsg()
@ -89,8 +89,8 @@ func (self *WhisperPeer) handshake() error {
if err != nil { if err != nil {
return fmt.Errorf("bad status message: %v", err) return fmt.Errorf("bad status message: %v", err)
} }
if peerVersion != protocolVersion { if peerVersion != ProtocolVersion {
return fmt.Errorf("protocol version mismatch %d != %d", peerVersion, protocolVersion) return fmt.Errorf("protocol version mismatch %d != %d", peerVersion, ProtocolVersion)
} }
// Wait until out own status is consumed too // Wait until out own status is consumed too
if err := <-errc; err != nil { if err := <-errc; err != nil {
@ -101,7 +101,7 @@ func (self *WhisperPeer) handshake() error {
// update executes periodic operations on the peer, including message transmission // update executes periodic operations on the peer, including message transmission
// and expiration. // and expiration.
func (self *WhisperPeer) update() { func (self *Peer) update() {
// Start the tickers for the updates // Start the tickers for the updates
expire := time.NewTicker(expirationCycle) expire := time.NewTicker(expirationCycle)
transmit := time.NewTicker(transmissionCycle) transmit := time.NewTicker(transmissionCycle)
@ -125,18 +125,18 @@ func (self *WhisperPeer) update() {
} }
// mark marks an envelope known to the peer so that it won't be sent back. // mark marks an envelope known to the peer so that it won't be sent back.
func (self *WhisperPeer) mark(envelope *Envelope) { func (self *Peer) mark(envelope *Envelope) {
self.known.Add(envelope.Hash()) self.known.Add(envelope.Hash())
} }
// marked checks if an envelope is already known to the remote peer. // marked checks if an envelope is already known to the remote peer.
func (self *WhisperPeer) marked(envelope *Envelope) bool { func (self *Peer) marked(envelope *Envelope) bool {
return self.known.Has(envelope.Hash()) return self.known.Has(envelope.Hash())
} }
// expire iterates over all the known envelopes in the host and removes all // expire iterates over all the known envelopes in the host and removes all
// expired (unknown) ones from the known list. // expired (unknown) ones from the known list.
func (self *WhisperPeer) expire() { func (self *Peer) expire() {
// Assemble the list of available envelopes // Assemble the list of available envelopes
available := set.NewNonTS() available := set.NewNonTS()
for _, envelope := range self.host.Envelopes() { for _, envelope := range self.host.Envelopes() {
@ -158,7 +158,7 @@ func (self *WhisperPeer) expire() {
// broadcast iterates over the collection of envelopes and transmits yet unknown // broadcast iterates over the collection of envelopes and transmits yet unknown
// ones over the network. // ones over the network.
func (self *WhisperPeer) broadcast() error { func (self *Peer) broadcast() error {
// Fetch the envelopes and collect the unknown ones // Fetch the envelopes and collect the unknown ones
envelopes := self.host.Envelopes() envelopes := self.host.Envelopes()
transmit := make([]*Envelope, 0, len(envelopes)) transmit := make([]*Envelope, 0, len(envelopes))

View file

@ -17,7 +17,7 @@
// Contains the Whisper protocol Topic element. For formal details please see // Contains the Whisper protocol Topic element. For formal details please see
// the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#topics. // the specs at https://github.com/ethereum/wiki/wiki/Whisper-PoC-1-Protocol-Spec#topics.
package whisper05 package whisperv5
import ( import (
"fmt" "fmt"
@ -29,11 +29,11 @@ import (
// Topic represents a cryptographically secure, probabilistic partial // Topic represents a cryptographically secure, probabilistic partial
// classifications of a message, determined as the first (left) 4 bytes of the // classifications of a message, determined as the first (left) 4 bytes of the
// SHA3 hash of some arbitrary data given by the original author of the message. // SHA3 hash of some arbitrary data given by the original author of the message.
type TopicType [topicLength]byte type TopicType [TopicLength]byte
func BytesToTopic(b []byte) (t TopicType) { func BytesToTopic(b []byte) (t TopicType) {
sz := topicLength sz := TopicLength
if x := len(b); x < topicLength { if x := len(b); x < TopicLength {
sz = x sz = x
} }
for i := 0; i < sz; i++ { for i := 0; i < sz; i++ {
@ -43,7 +43,7 @@ func BytesToTopic(b []byte) (t TopicType) {
} }
func HashToTopic(h common.Hash) (t TopicType) { func HashToTopic(h common.Hash) (t TopicType) {
for i := 0; i < topicLength; i++ { for i := 0; i < TopicLength; i++ {
t[i] = h[i] t[i] = h[i]
} }
return t return t
@ -65,12 +65,12 @@ func (t *TopicType) UnmarshalJSON(input []byte) error {
input = input[2:] input = input[2:]
} }
// validate the length of the input // validate the length of the input
if len(input) != topicLength*2 { if len(input) != TopicLength*2 {
return fmt.Errorf("whisper: unmarshalJSON failed: topic must be exactly %d bytes", topicLength) return fmt.Errorf("unmarshalJSON failed: topic must be exactly %d bytes", TopicLength)
} }
b := common.FromHex(string(input)) b := common.FromHex(string(input))
if b == nil { if b == nil {
return fmt.Errorf("whisper: unmarshalJSON failed: wrong topic format") return fmt.Errorf("unmarshalJSON failed: wrong topic format")
} }
*t = BytesToTopic(b) *t = BytesToTopic(b)
return nil return nil

View file

@ -14,7 +14,7 @@
// You should have received a copy of the GNU Lesser General Public License // 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/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package whisper05 package whisperv5
import ( import (
"bytes" "bytes"
@ -30,11 +30,8 @@ import (
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog" "github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/rpc"
"golang.org/x/crypto/pbkdf2"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"golang.org/x/crypto/pbkdf2"
set "gopkg.in/fatih/set.v0" set "gopkg.in/fatih/set.v0"
) )
@ -53,52 +50,40 @@ type Whisper struct {
expirations map[uint32]*set.SetNonTS // Message expiration pool expirations map[uint32]*set.SetNonTS // Message expiration pool
poolMu sync.RWMutex // Mutex to sync the message and expiration pools poolMu sync.RWMutex // Mutex to sync the message and expiration pools
peers map[*WhisperPeer]struct{} // Set of currently active peers peers map[*Peer]struct{} // Set of currently active peers
peerMu sync.RWMutex // Mutex to sync the active peer set peerMu sync.RWMutex // Mutex to sync the active peer set
mailServer *MailServer mailServer MailServer
quit chan struct{} quit chan struct{}
} }
// New creates a Whisper client ready to communicate through the Ethereum P2P network. // New creates a Whisper client ready to communicate through the Ethereum P2P network.
// Param s should be passed if you want to implement mail server, otherwise nil. // Param s should be passed if you want to implement mail server, otherwise nil.
func New(s *MailServer) *Whisper { func New(server MailServer) *Whisper {
whisper := &Whisper{ whisper := &Whisper{
privateKeys: make(map[string]*ecdsa.PrivateKey), privateKeys: make(map[string]*ecdsa.PrivateKey),
topicKeys: make(map[string][]byte), topicKeys: make(map[string][]byte),
envelopes: make(map[common.Hash]*Envelope), envelopes: make(map[common.Hash]*Envelope),
messages: make(map[common.Hash]*ReceivedMessage), messages: make(map[common.Hash]*ReceivedMessage),
expirations: make(map[uint32]*set.SetNonTS), expirations: make(map[uint32]*set.SetNonTS),
peers: make(map[*WhisperPeer]struct{}), peers: make(map[*Peer]struct{}),
mailServer: s, mailServer: server,
quit: make(chan struct{}), quit: make(chan struct{}),
} }
whisper.filters = NewFilters(whisper) whisper.filters = NewFilters(whisper)
// p2p whisper sub protocol handler // p2p whisper sub protocol handler
whisper.protocol = p2p.Protocol{ whisper.protocol = p2p.Protocol{
Name: protocolName, Name: ProtocolName,
Version: uint(protocolVersion), Version: uint(ProtocolVersion),
Length: 2, Length: NumberOfMessageCodes,
Run: whisper.handlePeer, Run: whisper.HandlePeer,
} }
return whisper return whisper
} }
// APIs returns the RPC descriptors the Whisper implementation offers
func (s *Whisper) APIs() []rpc.API {
return []rpc.API{
{
Namespace: protocolName,
Version: protocolVersionStr,
Service: NewPublicWhisperAPI(s),
Public: true,
},
}
}
// Protocols returns the whisper sub-protocols ran by this particular client. // Protocols returns the whisper sub-protocols ran by this particular client.
func (self *Whisper) Protocols() []p2p.Protocol { func (self *Whisper) Protocols() []p2p.Protocol {
return []p2p.Protocol{self.protocol} return []p2p.Protocol{self.protocol}
@ -109,58 +94,47 @@ func (self *Whisper) Version() uint {
return self.protocol.Version return self.protocol.Version
} }
// MarkPeerTrusted marks specific peer trusted, which will allow it func (self *Whisper) GetFilter(id int) *Filter {
// to send historic (expired) messages. return self.filters.Get(id)
func (self *Whisper) MarkPeerTrusted(peerID *rpc.HexBytes) error { }
func (self *Whisper) getPeer(peerID []byte) (*Peer, error) {
self.peerMu.Lock() self.peerMu.Lock()
defer self.peerMu.Unlock() defer self.peerMu.Unlock()
for p, _ := range self.peers { for p, _ := range self.peers {
id := p.peer.ID() id := p.peer.ID()
if bytes.Equal(*peerID, id[:]) { if bytes.Equal(peerID, id[:]) {
return p, nil
}
}
return nil, fmt.Errorf("Could not find peer with ID: %x", peerID)
}
// MarkPeerTrusted marks specific peer trusted, which will allow it
// to send historic (expired) messages.
func (self *Whisper) MarkPeerTrusted(peerID []byte) error {
p, err := self.getPeer(peerID)
if err != nil {
return err
}
p.trusted = true p.trusted = true
return nil return nil
} }
}
return fmt.Errorf("Could not find peer with ID: %x", peerID)
}
func (self *Whisper) RequestHistoricMessages(peerID *rpc.HexBytes, data *rpc.HexBytes) error { func (self *Whisper) RequestHistoricMessages(peerID []byte, data []byte) error {
var wp *WhisperPeer wp, err := self.getPeer(peerID)
self.peerMu.Lock() if err != nil {
for p, _ := range self.peers { return err
id := p.peer.ID()
if bytes.Equal(*peerID, id[:]) {
p.trusted = true
wp = p
break
} }
} wp.trusted = true
self.peerMu.Unlock()
if wp == nil {
return fmt.Errorf("RequestHistoricMessages: Could not find peer with ID: %x", peerID)
}
return p2p.Send(wp.ws, mailRequestCode, data) return p2p.Send(wp.ws, mailRequestCode, data)
} }
func (self *Whisper) SendP2PMessage(peerID *rpc.HexBytes, envelope *Envelope) error { func (self *Whisper) SendP2PMessage(peerID []byte, envelope *Envelope) error {
var wp *WhisperPeer wp, err := self.getPeer(peerID)
self.peerMu.Lock() if err != nil {
for p, _ := range self.peers { return err
id := p.peer.ID()
if bytes.Equal(*peerID, id[:]) {
p.trusted = true
wp = p
break
} }
}
self.peerMu.Unlock()
if wp == nil {
return fmt.Errorf("SendP2PMessage: Could not find peer with ID: %x", peerID)
}
return p2p.Send(wp.ws, p2pCode, envelope) return p2p.Send(wp.ws, p2pCode, envelope)
} }
@ -207,7 +181,7 @@ func (self *Whisper) GetIdentity(key *ecdsa.PublicKey) *ecdsa.PrivateKey {
func (self *Whisper) GenerateTopicKey(name string) error { func (self *Whisper) GenerateTopicKey(name string) error {
if self.HasTopicKey(name) { if self.HasTopicKey(name) {
return fmt.Errorf("GenerateTopicKey: key with name [%s] already exists", name) return fmt.Errorf("Key with name [%s] already exists", name)
} }
key := make([]byte, aesKeyLength) key := make([]byte, aesKeyLength)
@ -215,7 +189,7 @@ func (self *Whisper) GenerateTopicKey(name string) error {
if err != nil { if err != nil {
return err return err
} else if !validateSymmetricKey(key) { } else if !validateSymmetricKey(key) {
return fmt.Errorf("GenerateTopicKey: failed to generate valid key") return fmt.Errorf("crypto/rand failed to generate valid key")
} }
self.keyMu.Lock() self.keyMu.Lock()
@ -226,10 +200,10 @@ func (self *Whisper) GenerateTopicKey(name string) error {
func (self *Whisper) AddTopicKey(name string, key []byte) error { func (self *Whisper) AddTopicKey(name string, key []byte) error {
if self.HasTopicKey(name) { if self.HasTopicKey(name) {
return fmt.Errorf("AddTopicKey: key with name [%s] already exists", name) return fmt.Errorf("Key with name [%s] already exists", name)
} }
derived, err := DeriveKeyMaterial(key, EnvelopeVersion) derived, err := deriveKeyMaterial(key, EnvelopeVersion)
if err != nil { if err != nil {
return err return err
} }
@ -293,7 +267,7 @@ func (self *Whisper) Stop() error {
// handlePeer is called by the underlying P2P layer when the whisper sub-protocol // handlePeer is called by the underlying P2P layer when the whisper sub-protocol
// connection is negotiated. // connection is negotiated.
func (self *Whisper) handlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error { func (self *Whisper) HandlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
// Create the new peer and start tracking it // Create the new peer and start tracking it
whisperPeer := newPeer(self, peer, rw) whisperPeer := newPeer(self, peer, rw)
@ -318,7 +292,7 @@ func (self *Whisper) handlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
} }
// runMessageLoop reads and processes inbound messages directly to merge into client-global state. // runMessageLoop reads and processes inbound messages directly to merge into client-global state.
func (self *Whisper) runMessageLoop(p *WhisperPeer, rw p2p.MsgReadWriter) error { func (self *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
for { for {
// fetch the next packet // fetch the next packet
packet, err := rw.ReadMsg() packet, err := rw.ReadMsg()
@ -345,7 +319,7 @@ func (self *Whisper) runMessageLoop(p *WhisperPeer, rw p2p.MsgReadWriter) error
} }
p.mark(envelope) p.mark(envelope)
if self.mailServer != nil { if self.mailServer != nil {
(*self.mailServer).Archive(envelope) self.mailServer.Archive(envelope)
} }
} }
case p2pCode: case p2pCode:
@ -369,7 +343,7 @@ func (self *Whisper) runMessageLoop(p *WhisperPeer, rw p2p.MsgReadWriter) error
s := rlp.NewStream(packet.Payload, uint64(packet.Size)) s := rlp.NewStream(packet.Payload, uint64(packet.Size))
data, err := s.Bytes() data, err := s.Bytes()
if err == nil { if err == nil {
(*self.mailServer).DeliverMail(p, data) self.mailServer.DeliverMail(p, data)
} else { } else {
glog.V(logger.Error).Infof("%v: bad requestHistoricMessages received: [%v]", p.peer, err) glog.V(logger.Error).Infof("%v: bad requestHistoricMessages received: [%v]", p.peer, err)
} }
@ -378,6 +352,8 @@ func (self *Whisper) runMessageLoop(p *WhisperPeer, rw p2p.MsgReadWriter) error
// New message types might be implemented in the future versions of Whisper. // New message types might be implemented in the future versions of Whisper.
// For forward compatibility, just ignore. // For forward compatibility, just ignore.
} }
packet.Discard()
} }
} }
@ -405,7 +381,7 @@ func (self *Whisper) add(envelope *Envelope) error {
} }
} }
if len(envelope.Data) > msgMaxLength { if len(envelope.Data) > MaxMessageLength {
return fmt.Errorf("huge messages are not allowed") return fmt.Errorf("huge messages are not allowed")
} }
@ -524,7 +500,7 @@ func (self *Whisper) addDecryptedMessage(msg *ReceivedMessage) {
self.messages[msg.EnvelopeHash] = msg self.messages[msg.EnvelopeHash] = msg
} }
func validatePublicKey(k *ecdsa.PublicKey) bool { func ValidatePublicKey(k *ecdsa.PublicKey) bool {
return k != nil && k.X != nil && k.Y != nil && k.X.Sign() != 0 && k.Y.Sign() != 0 return k != nil && k.X != nil && k.Y != nil && k.X.Sign() != 0 && k.Y.Sign() != 0
} }
@ -532,16 +508,12 @@ func validatePrivateKey(k *ecdsa.PrivateKey) bool {
if k == nil || k.D == nil || k.D.Sign() == 0 { if k == nil || k.D == nil || k.D.Sign() == 0 {
return false return false
} }
return validatePublicKey(&k.PublicKey) return ValidatePublicKey(&k.PublicKey)
} }
// validateSymmetricKey returns false if the key contains all zeros // validateSymmetricKey returns false if the key contains all zeros
func validateSymmetricKey(k []byte) bool { func validateSymmetricKey(k []byte) bool {
if len(k) == 0 { return len(k) > 0 && !containsOnlyZeros(k)
return false
}
empty := containsOnlyZeros(k)
return !empty
} }
func containsOnlyZeros(data []byte) bool { func containsOnlyZeros(data []byte) bool {
@ -559,25 +531,25 @@ func bytesToIntLittleEndian(b []byte) (res uint64) {
res += uint64(b[i]) * mul res += uint64(b[i]) * mul
mul *= 256 mul *= 256
} }
return return res
} }
func bytesToIntBigEndian(b []byte) (res uint64) { func BytesToIntBigEndian(b []byte) (res uint64) {
for i := 0; i < len(b); i++ { for i := 0; i < len(b); i++ {
res *= 256 res *= 256
res += uint64(b[i]) res += uint64(b[i])
} }
return return res
} }
// DeriveSymmetricKey derives symmetric key material from the key or password. // DeriveSymmetricKey derives symmetric key material from the key or password.
// pbkdf2 is used for security, in case people use password instead of randomly generated keys. // 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) { func deriveKeyMaterial(key []byte, version uint64) (derivedKey []byte, err error) {
if version == 0 { if version == 0 {
// todo: review: kdf should run no less than 1 sec, because it's a once in a session experience // todo: review: kdf should run no less than 1 sec, because it's a once in a session experience
derivedKey = pbkdf2.Key(key, nil, 65356, aesKeyLength, sha256.New) derivedKey := pbkdf2.Key(key, nil, 65356, aesKeyLength, sha256.New)
return derivedKey, nil
} else { } else {
err = fmt.Errorf("DeriveSymmetricKey: invalid envelope version: %d", version) return nil, unknownVersionError(version)
} }
return
} }