whisper/shhapi, whisper/whisperv5: refactoring (#3364)

* Filter refactoring
* API tests added + bugfix
* fixed the error logs
* FilterID fixed
* test cases fixed
* key generation updated
* POW updated
* got rid of redundant stuff
This commit is contained in:
gluk256 2016-12-01 20:09:22 +01:00 committed by Felix Lange
parent 671fd94e25
commit 2dcf75a722
14 changed files with 830 additions and 652 deletions

View File

@ -149,13 +149,13 @@ func (api *PublicWhisperAPI) DeleteSymKey(name string) error {
// NewWhisperFilter creates and registers a new message filter to watch for inbound whisper messages. // NewWhisperFilter creates and registers a new message filter to watch for inbound whisper messages.
// Returns the ID of the newly created Filter. // Returns the ID of the newly created Filter.
func (api *PublicWhisperAPI) NewFilter(args WhisperFilterArgs) (*rpc.HexNumber, error) { func (api *PublicWhisperAPI) NewFilter(args WhisperFilterArgs) (uint32, error) {
if api.whisper == nil { if api.whisper == nil {
return nil, whisperOffLineErr return 0, whisperOffLineErr
} }
filter := whisperv5.Filter{ filter := whisperv5.Filter{
Src: crypto.ToECDSAPub(args.From), Src: crypto.ToECDSAPub(common.FromHex(args.From)),
KeySym: api.whisper.GetSymKey(args.KeyName), KeySym: api.whisper.GetSymKey(args.KeyName),
PoW: args.PoW, PoW: args.PoW,
Messages: make(map[common.Hash]*whisperv5.ReceivedMessage), Messages: make(map[common.Hash]*whisperv5.ReceivedMessage),
@ -173,39 +173,39 @@ func (api *PublicWhisperAPI) NewFilter(args WhisperFilterArgs) (*rpc.HexNumber,
if len(args.Topics) == 0 { if len(args.Topics) == 0 {
info := "NewFilter: at least one topic must be specified" info := "NewFilter: at least one topic must be specified"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return nil, errors.New(info) return 0, errors.New(info)
} }
if len(args.KeyName) != 0 && len(filter.KeySym) == 0 { if len(args.KeyName) != 0 && len(filter.KeySym) == 0 {
info := "NewFilter: key was not found by name: " + args.KeyName info := "NewFilter: key was not found by name: " + args.KeyName
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return nil, errors.New(info) return 0, errors.New(info)
} }
if len(args.To) == 0 && len(filter.KeySym) == 0 { if len(args.To) == 0 && len(filter.KeySym) == 0 {
info := "NewFilter: filter must contain either symmetric or asymmetric key" info := "NewFilter: filter must contain either symmetric or asymmetric key"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return nil, errors.New(info) return 0, errors.New(info)
} }
if len(args.To) != 0 && len(filter.KeySym) != 0 { if len(args.To) != 0 && len(filter.KeySym) != 0 {
info := "NewFilter: filter must not contain both symmetric and asymmetric key" info := "NewFilter: filter must not contain both symmetric and asymmetric key"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return nil, errors.New(info) return 0, errors.New(info)
} }
if len(args.To) > 0 { if len(args.To) > 0 {
dst := crypto.ToECDSAPub(args.To) dst := crypto.ToECDSAPub(common.FromHex(args.To))
if !whisperv5.ValidatePublicKey(dst) { if !whisperv5.ValidatePublicKey(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 0, errors.New(info)
} }
filter.KeyAsym = api.whisper.GetIdentity(string(args.To)) filter.KeyAsym = api.whisper.GetIdentity(string(args.To))
if filter.KeyAsym == nil { if filter.KeyAsym == nil {
info := "NewFilter: non-existent identity provided" info := "NewFilter: non-existent identity provided"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return nil, errors.New(info) return 0, errors.New(info)
} }
} }
@ -213,22 +213,22 @@ func (api *PublicWhisperAPI) NewFilter(args WhisperFilterArgs) (*rpc.HexNumber,
if !whisperv5.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 0, errors.New(info)
} }
} }
id := api.whisper.Watch(&filter) id := api.whisper.Watch(&filter)
return rpc.NewHexNumber(id), nil return id, nil
} }
// UninstallFilter disables and removes an existing filter. // UninstallFilter disables and removes an existing filter.
func (api *PublicWhisperAPI) UninstallFilter(filterId rpc.HexNumber) { func (api *PublicWhisperAPI) UninstallFilter(filterId uint32) {
api.whisper.Unwatch(filterId.Int()) api.whisper.Unwatch(filterId)
} }
// 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 (api *PublicWhisperAPI) GetFilterChanges(filterId rpc.HexNumber) []WhisperMessage { func (api *PublicWhisperAPI) GetFilterChanges(filterId uint32) []WhisperMessage {
f := api.whisper.GetFilter(filterId.Int()) f := api.whisper.GetFilter(filterId)
if f != nil { if f != nil {
newMail := f.Retrieve() newMail := f.Retrieve()
return toWhisperMessages(newMail) return toWhisperMessages(newMail)
@ -237,8 +237,8 @@ func (api *PublicWhisperAPI) GetFilterChanges(filterId rpc.HexNumber) []WhisperM
} }
// GetMessages retrieves all the known messages that match a specific filter. // GetMessages retrieves all the known messages that match a specific filter.
func (api *PublicWhisperAPI) GetMessages(filterId rpc.HexNumber) []WhisperMessage { func (api *PublicWhisperAPI) GetMessages(filterId uint32) []WhisperMessage {
all := api.whisper.Messages(filterId.Int()) all := api.whisper.Messages(filterId)
return toWhisperMessages(all) return toWhisperMessages(all)
} }
@ -259,7 +259,7 @@ func (api *PublicWhisperAPI) Post(args PostArgs) error {
params := whisperv5.MessageParams{ params := whisperv5.MessageParams{
TTL: args.TTL, TTL: args.TTL,
Dst: crypto.ToECDSAPub(args.To), Dst: crypto.ToECDSAPub(common.FromHex(args.To)),
KeySym: api.whisper.GetSymKey(args.KeyName), KeySym: api.whisper.GetSymKey(args.KeyName),
Topic: args.Topic, Topic: args.Topic,
Payload: args.Payload, Payload: args.Payload,
@ -269,7 +269,7 @@ func (api *PublicWhisperAPI) Post(args PostArgs) error {
} }
if len(args.From) > 0 { if len(args.From) > 0 {
pub := crypto.ToECDSAPub(args.From) pub := crypto.ToECDSAPub(common.FromHex(args.From))
if !whisperv5.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)
@ -284,7 +284,7 @@ func (api *PublicWhisperAPI) Post(args PostArgs) error {
} }
filter := api.whisper.GetFilter(args.FilterID) filter := api.whisper.GetFilter(args.FilterID)
if filter == nil && args.FilterID > -1 { if filter == nil && args.FilterID > 0 {
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)
return errors.New(info) return errors.New(info)
@ -321,13 +321,13 @@ func (api *PublicWhisperAPI) Post(args PostArgs) error {
return errors.New(info) return errors.New(info)
} }
if len(args.To) == 0 && len(args.KeyName) == 0 { if len(args.To) == 0 && len(params.KeySym) == 0 {
info := "Post: message must be encrypted either symmetrically or asymmetrically" info := "Post: message must be encrypted either symmetrically or asymmetrically"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return errors.New(info) return errors.New(info)
} }
if len(args.To) != 0 && len(args.KeyName) != 0 { if len(args.To) != 0 && len(params.KeySym) != 0 {
info := "Post: ambigous encryption method requested" info := "Post: ambigous encryption method requested"
glog.V(logger.Error).Infof(info) glog.V(logger.Error).Infof(info)
return errors.New(info) return errors.New(info)
@ -368,60 +368,21 @@ func (api *PublicWhisperAPI) Post(args PostArgs) error {
type PostArgs struct { type PostArgs struct {
TTL uint32 `json:"ttl"` TTL uint32 `json:"ttl"`
From rpc.HexBytes `json:"from"` From string `json:"from"`
To rpc.HexBytes `json:"to"` To string `json:"to"`
KeyName string `json:"keyname"` KeyName string `json:"keyname"`
Topic whisperv5.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 uint32 `json:"filterID"`
PeerID rpc.HexBytes `json:"directP2P"` PeerID rpc.HexBytes `json:"peerID"`
}
func (args *PostArgs) UnmarshalJSON(data []byte) (err error) {
var obj struct {
TTL uint32 `json:"ttl"`
From rpc.HexBytes `json:"from"`
To rpc.HexBytes `json:"to"`
KeyName string `json:"keyname"`
Topic whisperv5.TopicType `json:"topic"`
Payload rpc.HexBytes `json:"payload"`
Padding rpc.HexBytes `json:"padding"`
WorkTime uint32 `json:"worktime"`
PoW float64 `json:"pow"`
FilterID rpc.HexBytes `json:"filter"`
PeerID rpc.HexBytes `json:"directP2P"`
}
if err := json.Unmarshal(data, &obj); err != nil {
return err
}
args.TTL = obj.TTL
args.From = obj.From
args.To = obj.To
args.KeyName = obj.KeyName
args.Topic = obj.Topic
args.Payload = obj.Payload
args.Padding = obj.Padding
args.WorkTime = obj.WorkTime
args.PoW = obj.PoW
args.FilterID = -1
args.PeerID = obj.PeerID
if obj.FilterID != nil {
x := whisperv5.BytesToIntBigEndian(obj.FilterID)
args.FilterID = int(x)
}
return nil
} }
type WhisperFilterArgs struct { type WhisperFilterArgs struct {
To []byte To string
From []byte From string
KeyName string KeyName string
PoW float64 PoW float64
Topics []whisperv5.TopicType Topics []whisperv5.TopicType
@ -433,8 +394,8 @@ type WhisperFilterArgs struct {
func (args *WhisperFilterArgs) UnmarshalJSON(b []byte) (err error) { func (args *WhisperFilterArgs) UnmarshalJSON(b []byte) (err error) {
// Unmarshal the JSON message and sanity check // Unmarshal the JSON message and sanity check
var obj struct { var obj struct {
To rpc.HexBytes `json:"to"` To string `json:"to"`
From rpc.HexBytes `json:"from"` From string `json:"from"`
KeyName string `json:"keyname"` KeyName string `json:"keyname"`
PoW float64 `json:"pow"` PoW float64 `json:"pow"`
Topics []interface{} `json:"topics"` Topics []interface{} `json:"topics"`

View File

@ -17,88 +17,77 @@
package shhapi package shhapi
import ( import (
"bytes"
"testing" "testing"
"time"
"github.com/ethereum/go-ethereum/rpc" "encoding/json"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/whisper/whisperv5" "github.com/ethereum/go-ethereum/whisper/whisperv5"
) )
func TestBasic(x *testing.T) { func TestBasic(t *testing.T) {
var id string = "test" var id string = "test"
api := NewPublicWhisperAPI() api := NewPublicWhisperAPI()
if api == nil { if api == nil {
x.Errorf("failed to create API.") t.Fatalf("failed to create API.")
return
} }
ver, err := api.Version() ver, err := api.Version()
if err != nil { if err != nil {
x.Errorf("failed generateFilter: %s.", err) t.Fatalf("failed generateFilter: %s.", err)
return
} }
if ver.Uint64() != whisperv5.ProtocolVersion { if ver.Uint64() != whisperv5.ProtocolVersion {
x.Errorf("wrong version: %d.", ver.Uint64()) t.Fatalf("wrong version: %d.", ver.Uint64())
return
} }
var hexnum rpc.HexNumber mail := api.GetFilterChanges(1)
mail := api.GetFilterChanges(hexnum)
if len(mail) != 0 { if len(mail) != 0 {
x.Errorf("failed GetFilterChanges") t.Fatalf("failed GetFilterChanges: premature result")
return
} }
exist, err := api.HasIdentity(id) exist, err := api.HasIdentity(id)
if err != nil { if err != nil {
x.Errorf("failed 1 HasIdentity: %s.", err) t.Fatalf("failed initial HasIdentity: %s.", err)
return
} }
if exist { if exist {
x.Errorf("failed 2 HasIdentity: false positive.") t.Fatalf("failed initial HasIdentity: false positive.")
return
} }
err = api.DeleteIdentity(id) err = api.DeleteIdentity(id)
if err != nil { if err != nil {
x.Errorf("failed 3 DeleteIdentity: %s.", err) t.Fatalf("failed DeleteIdentity: %s.", err)
return
} }
pub, err := api.NewIdentity() pub, err := api.NewIdentity()
if err != nil { if err != nil {
x.Errorf("failed 4 NewIdentity: %s.", err) t.Fatalf("failed NewIdentity: %s.", err)
return
} }
if len(pub) == 0 { if len(pub) == 0 {
x.Errorf("NewIdentity 5: empty") t.Fatalf("failed NewIdentity: empty")
return
} }
exist, err = api.HasIdentity(pub) exist, err = api.HasIdentity(pub)
if err != nil { if err != nil {
x.Errorf("failed 6 HasIdentity: %s.", err) t.Fatalf("failed HasIdentity: %s.", err)
return
} }
if !exist { if !exist {
x.Errorf("failed 7 HasIdentity: false negative.") t.Fatalf("failed HasIdentity: false negative.")
return
} }
err = api.DeleteIdentity(pub) err = api.DeleteIdentity(pub)
if err != nil { if err != nil {
x.Errorf("failed 8 DeleteIdentity: %s.", err) t.Fatalf("failed to delete second identity: %s.", err)
return
} }
exist, err = api.HasIdentity(pub) exist, err = api.HasIdentity(pub)
if err != nil { if err != nil {
x.Errorf("failed 9 HasIdentity: %s.", err) t.Fatalf("failed HasIdentity(): %s.", err)
return
} }
if exist { if exist {
x.Errorf("failed 10 HasIdentity: false positive.") t.Fatalf("failed HasIdentity(): false positive.")
return
} }
id = "arbitrary text" id = "arbitrary text"
@ -106,65 +95,468 @@ func TestBasic(x *testing.T) {
exist, err = api.HasSymKey(id) exist, err = api.HasSymKey(id)
if err != nil { if err != nil {
x.Errorf("failed 11 HasSymKey: %s.", err) t.Fatalf("failed HasSymKey: %s.", err)
return
} }
if exist { if exist {
x.Errorf("failed 12 HasSymKey: false positive.") t.Fatalf("failed HasSymKey: false positive.")
return
} }
err = api.GenerateSymKey(id) err = api.GenerateSymKey(id)
if err != nil { if err != nil {
x.Errorf("failed 13 GenerateSymKey: %s.", err) t.Fatalf("failed GenerateSymKey: %s.", err)
return
} }
exist, err = api.HasSymKey(id) exist, err = api.HasSymKey(id)
if err != nil { if err != nil {
x.Errorf("failed 14 HasSymKey: %s.", err) t.Fatalf("failed HasSymKey(): %s.", err)
return
} }
if !exist { if !exist {
x.Errorf("failed 15 HasSymKey: false negative.") t.Fatalf("failed HasSymKey(): false negative.")
return
} }
err = api.AddSymKey(id, []byte("some stuff here")) err = api.AddSymKey(id, []byte("some stuff here"))
if err == nil { if err == nil {
x.Errorf("failed 16 AddSymKey: %s.", err) t.Fatalf("failed AddSymKey: %s.", err)
return
} }
err = api.AddSymKey(id2, []byte("some stuff here")) err = api.AddSymKey(id2, []byte("some stuff here"))
if err != nil { if err != nil {
x.Errorf("failed 17 AddSymKey: %s.", err) t.Fatalf("failed AddSymKey: %s.", err)
return
} }
exist, err = api.HasSymKey(id2) exist, err = api.HasSymKey(id2)
if err != nil { if err != nil {
x.Errorf("failed 18 HasSymKey: %s.", err) t.Fatalf("failed HasSymKey(id2): %s.", err)
return
} }
if !exist { if !exist {
x.Errorf("failed 19 HasSymKey: false negative.") t.Fatalf("failed HasSymKey(id2): false negative.")
return
} }
err = api.DeleteSymKey(id) err = api.DeleteSymKey(id)
if err != nil { if err != nil {
x.Errorf("failed 20 DeleteSymKey: %s.", err) t.Fatalf("failed DeleteSymKey(id): %s.", err)
return
} }
exist, err = api.HasSymKey(id) exist, err = api.HasSymKey(id)
if err != nil { if err != nil {
x.Errorf("failed 21 HasSymKey: %s.", err) t.Fatalf("failed HasSymKey(id): %s.", err)
return
} }
if exist { if exist {
x.Errorf("failed 22 HasSymKey: false positive.") t.Fatalf("failed HasSymKey(id): false positive.")
return }
}
func TestUnmarshalFilterArgs(t *testing.T) {
s := []byte(`{
"to":"0x70c87d191324e6712a591f304b4eedef6ad9bb9d",
"from":"0x9b2055d370f73ec7d8a03e965129118dc8f5bf83",
"keyname":"testname",
"pow":2.34,
"topics":["0x00000000", "0x007f80ff", "0xff807f00", "0xf26e7779"],
"acceptP2P":true
}`)
var f WhisperFilterArgs
err := f.UnmarshalJSON(s)
if err != nil {
t.Fatalf("failed UnmarshalJSON: %s.", err)
}
if f.To != "0x70c87d191324e6712a591f304b4eedef6ad9bb9d" {
t.Fatalf("wrong To: %x.", f.To)
}
if f.From != "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83" {
t.Fatalf("wrong From: %x.", f.To)
}
if f.KeyName != "testname" {
t.Fatalf("wrong KeyName: %s.", f.KeyName)
}
if f.PoW != 2.34 {
t.Fatalf("wrong pow: %f.", f.PoW)
}
if !f.AcceptP2P {
t.Fatalf("wrong AcceptP2P: %v.", f.AcceptP2P)
}
if len(f.Topics) != 4 {
t.Fatalf("wrong topics number: %d.", len(f.Topics))
}
i := 0
if f.Topics[i] != (whisperv5.TopicType{0x00, 0x00, 0x00, 0x00}) {
t.Fatalf("wrong topic[%d]: %x.", i, f.Topics[i])
}
i++
if f.Topics[i] != (whisperv5.TopicType{0x00, 0x7f, 0x80, 0xff}) {
t.Fatalf("wrong topic[%d]: %x.", i, f.Topics[i])
}
i++
if f.Topics[i] != (whisperv5.TopicType{0xff, 0x80, 0x7f, 0x00}) {
t.Fatalf("wrong topic[%d]: %x.", i, f.Topics[i])
}
i++
if f.Topics[i] != (whisperv5.TopicType{0xf2, 0x6e, 0x77, 0x79}) {
t.Fatalf("wrong topic[%d]: %x.", i, f.Topics[i])
}
}
func TestUnmarshalPostArgs(t *testing.T) {
s := []byte(`{
"ttl":12345,
"from":"0x70c87d191324e6712a591f304b4eedef6ad9bb9d",
"to":"0x9b2055d370f73ec7d8a03e965129118dc8f5bf83",
"keyname":"shh_test",
"topic":"0xf26e7779",
"padding":"0x74686973206973206D79207465737420737472696E67",
"payload":"0x7061796C6F61642073686F756C642062652070736575646F72616E646F6D",
"worktime":777,
"pow":3.1416,
"filterID":64,
"peerID":"0xf26e7779"
}`)
var a PostArgs
err := json.Unmarshal(s, &a)
if err != nil {
t.Fatalf("failed UnmarshalJSON: %s.", err)
}
if a.TTL != 12345 {
t.Fatalf("wrong ttl: %d.", a.TTL)
}
if a.From != "0x70c87d191324e6712a591f304b4eedef6ad9bb9d" {
t.Fatalf("wrong From: %x.", a.To)
}
if a.To != "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83" {
t.Fatalf("wrong To: %x.", a.To)
}
if a.KeyName != "shh_test" {
t.Fatalf("wrong KeyName: %s.", a.KeyName)
}
if a.Topic != (whisperv5.TopicType{0xf2, 0x6e, 0x77, 0x79}) {
t.Fatalf("wrong topic: %x.", a.Topic)
}
if string(a.Padding) != "this is my test string" {
t.Fatalf("wrong Padding: %s.", string(a.Padding))
}
if string(a.Payload) != "payload should be pseudorandom" {
t.Fatalf("wrong Payload: %s.", string(a.Payload))
}
if a.WorkTime != 777 {
t.Fatalf("wrong WorkTime: %d.", a.WorkTime)
}
if a.PoW != 3.1416 {
t.Fatalf("wrong pow: %f.", a.PoW)
}
if a.FilterID != 64 {
t.Fatalf("wrong FilterID: %d.", a.FilterID)
}
if bytes.Compare(a.PeerID[:], a.Topic[:]) != 0 {
t.Fatalf("wrong PeerID: %x.", a.PeerID)
}
}
func waitForMessage(api *PublicWhisperAPI, id uint32, target int) bool {
for i := 0; i < 64; i++ {
all := api.GetMessages(id)
if len(all) >= target {
return true
}
time.Sleep(time.Millisecond * 16)
}
// timeout 1024 milliseconds
return false
}
func TestIntegrationAsym(t *testing.T) {
api := NewPublicWhisperAPI()
if api == nil {
t.Fatalf("failed to create API.")
}
sig, err := api.NewIdentity()
if err != nil {
t.Fatalf("failed NewIdentity: %s.", err)
}
if len(sig) == 0 {
t.Fatalf("wrong signature")
}
exist, err := api.HasIdentity(sig)
if err != nil {
t.Fatalf("failed HasIdentity: %s.", err)
}
if !exist {
t.Fatalf("failed HasIdentity: false negative.")
}
key, err := api.NewIdentity()
if err != nil {
t.Fatalf("failed NewIdentity(): %s.", err)
}
if len(key) == 0 {
t.Fatalf("wrong key")
}
var topics [2]whisperv5.TopicType
topics[0] = whisperv5.TopicType{0x00, 0x64, 0x00, 0xff}
topics[1] = whisperv5.TopicType{0xf2, 0x6e, 0x77, 0x79}
var f WhisperFilterArgs
f.To = key
f.From = sig
f.Topics = topics[:]
f.PoW = whisperv5.MinimumPoW / 2
f.AcceptP2P = true
id, err := api.NewFilter(f)
if err != nil {
t.Fatalf("failed to create new filter: %s.", err)
}
var p PostArgs
p.TTL = 2
p.From = f.From
p.To = f.To
p.Padding = []byte("test string")
p.Payload = []byte("extended test string")
p.PoW = whisperv5.MinimumPoW
p.Topic = whisperv5.TopicType{0xf2, 0x6e, 0x77, 0x79}
p.WorkTime = 2
err = api.Post(p)
if err != nil {
t.Errorf("failed to post message: %s.", err)
}
ok := waitForMessage(api, id, 1)
if !ok {
t.Fatalf("failed to receive first message: timeout.")
}
mail := api.GetFilterChanges(id)
if len(mail) != 1 {
t.Fatalf("failed to GetFilterChanges: got %d messages.", len(mail))
}
text := string(common.FromHex(mail[0].Payload))
if text != string("extended test string") {
t.Fatalf("failed to decrypt first message: %s.", text)
}
p.Padding = []byte("new value")
p.Payload = []byte("extended new value")
err = api.Post(p)
if err != nil {
t.Fatalf("failed to post next message: %s.", err)
}
ok = waitForMessage(api, id, 2)
if !ok {
t.Fatalf("failed to receive second message: timeout.")
}
mail = api.GetFilterChanges(id)
if len(mail) != 1 {
t.Fatalf("failed to GetFilterChanges: got %d messages.", len(mail))
}
text = string(common.FromHex(mail[0].Payload))
if text != string("extended new value") {
t.Fatalf("failed to decrypt second message: %s.", text)
}
}
func TestIntegrationSym(t *testing.T) {
api := NewPublicWhisperAPI()
if api == nil {
t.Fatalf("failed to create API.")
}
keyname := "schluessel"
err := api.GenerateSymKey(keyname)
if err != nil {
t.Fatalf("failed GenerateSymKey: %s.", err)
}
sig, err := api.NewIdentity()
if err != nil {
t.Fatalf("failed NewIdentity: %s.", err)
}
if len(sig) == 0 {
t.Fatalf("wrong signature")
}
exist, err := api.HasIdentity(sig)
if err != nil {
t.Fatalf("failed HasIdentity: %s.", err)
}
if !exist {
t.Fatalf("failed HasIdentity: false negative.")
}
var topics [2]whisperv5.TopicType
topics[0] = whisperv5.TopicType{0x00, 0x7f, 0x80, 0xff}
topics[1] = whisperv5.TopicType{0xf2, 0x6e, 0x77, 0x79}
var f WhisperFilterArgs
f.KeyName = keyname
f.Topics = topics[:]
f.PoW = 0.324
f.From = sig
f.AcceptP2P = false
id, err := api.NewFilter(f)
if err != nil {
t.Fatalf("failed to create new filter: %s.", err)
}
var p PostArgs
p.TTL = 1
p.KeyName = keyname
p.From = f.From
p.Padding = []byte("test string")
p.Payload = []byte("extended test string")
p.PoW = whisperv5.MinimumPoW
p.Topic = whisperv5.TopicType{0xf2, 0x6e, 0x77, 0x79}
p.WorkTime = 2
err = api.Post(p)
if err != nil {
t.Fatalf("failed to post first message: %s.", err)
}
ok := waitForMessage(api, id, 1)
if !ok {
t.Fatalf("failed to receive first message: timeout.")
}
mail := api.GetFilterChanges(id)
if len(mail) != 1 {
t.Fatalf("failed GetFilterChanges: got %d messages.", len(mail))
}
text := string(common.FromHex(mail[0].Payload))
if text != string("extended test string") {
t.Fatalf("failed to decrypt first message: %s.", text)
}
p.Padding = []byte("new value")
p.Payload = []byte("extended new value")
err = api.Post(p)
if err != nil {
t.Fatalf("failed to post second message: %s.", err)
}
ok = waitForMessage(api, id, 2)
if !ok {
t.Fatalf("failed to receive second message: timeout.")
}
mail = api.GetFilterChanges(id)
if len(mail) != 1 {
t.Fatalf("failed second GetFilterChanges: got %d messages.", len(mail))
}
text = string(common.FromHex(mail[0].Payload))
if text != string("extended new value") {
t.Fatalf("failed to decrypt second message: %s.", text)
}
}
func TestIntegrationSymWithFilter(t *testing.T) {
api := NewPublicWhisperAPI()
if api == nil {
t.Fatalf("failed to create API.")
}
keyname := "schluessel"
err := api.GenerateSymKey(keyname)
if err != nil {
t.Fatalf("failed to GenerateSymKey: %s.", err)
}
sig, err := api.NewIdentity()
if err != nil {
t.Fatalf("failed NewIdentity: %s.", err)
}
if len(sig) == 0 {
t.Fatalf("wrong signature.")
}
exist, err := api.HasIdentity(sig)
if err != nil {
t.Fatalf("failed HasIdentity: %s.", err)
}
if !exist {
t.Fatalf("failed HasIdentity: does not exist.")
}
var topics [2]whisperv5.TopicType
topics[0] = whisperv5.TopicType{0x00, 0x7f, 0x80, 0xff}
topics[1] = whisperv5.TopicType{0xf2, 0x6e, 0x77, 0x79}
var f WhisperFilterArgs
f.KeyName = keyname
f.Topics = topics[:]
f.PoW = 0.324
f.From = sig
f.AcceptP2P = false
id, err := api.NewFilter(f)
if err != nil {
t.Fatalf("failed to create new filter: %s.", err)
}
var p PostArgs
p.TTL = 1
p.FilterID = id
p.From = sig
p.Padding = []byte("test string")
p.Payload = []byte("extended test string")
p.PoW = whisperv5.MinimumPoW
p.Topic = whisperv5.TopicType{0xf2, 0x6e, 0x77, 0x79}
p.WorkTime = 2
err = api.Post(p)
if err != nil {
t.Fatalf("failed to post message: %s.", err)
}
ok := waitForMessage(api, id, 1)
if !ok {
t.Fatalf("failed to receive first message: timeout.")
}
mail := api.GetFilterChanges(id)
if len(mail) != 1 {
t.Fatalf("failed to GetFilterChanges: got %d messages.", len(mail))
}
text := string(common.FromHex(mail[0].Payload))
if text != string("extended test string") {
t.Fatalf("failed to decrypt first message: %s.", text)
}
p.Padding = []byte("new value")
p.Payload = []byte("extended new value")
err = api.Post(p)
if err != nil {
t.Fatalf("failed to post next message: %s.", err)
}
ok = waitForMessage(api, id, 2)
if !ok {
t.Fatalf("failed to receive second message: timeout.")
}
mail = api.GetFilterChanges(id)
if len(mail) != 1 {
t.Fatalf("failed to GetFilterChanges: got %d messages.", len(mail))
}
text = string(common.FromHex(mail[0].Payload))
if text != string("extended new value") {
t.Fatalf("failed to decrypt second message: %s.", text)
} }
} }

View File

@ -40,8 +40,7 @@ func BenchmarkEncryptionSym(b *testing.B) {
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
b.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) b.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -60,13 +59,11 @@ func BenchmarkEncryptionAsym(b *testing.B) {
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
b.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) b.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
key, err := crypto.GenerateKey() key, err := crypto.GenerateKey()
if err != nil { if err != nil {
b.Errorf("failed GenerateKey with seed %d: %s.", seed, err) b.Fatalf("failed GenerateKey with seed %d: %s.", seed, err)
return
} }
params.KeySym = nil params.KeySym = nil
params.Dst = &key.PublicKey params.Dst = &key.PublicKey
@ -75,8 +72,7 @@ func BenchmarkEncryptionAsym(b *testing.B) {
msg := NewSentMessage(params) msg := NewSentMessage(params)
_, err := msg.Wrap(params) _, err := msg.Wrap(params)
if err != nil { if err != nil {
b.Errorf("failed Wrap with seed %d: %s.", seed, err) b.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
} }
} }
@ -86,22 +82,19 @@ func BenchmarkDecryptionSymValid(b *testing.B) {
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
b.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) b.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
msg := NewSentMessage(params) msg := NewSentMessage(params)
env, err := msg.Wrap(params) env, err := msg.Wrap(params)
if err != nil { if err != nil {
b.Errorf("failed Wrap with seed %d: %s.", seed, err) b.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
f := Filter{KeySym: params.KeySym} f := Filter{KeySym: params.KeySym}
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
msg := env.Open(&f) msg := env.Open(&f)
if msg == nil { if msg == nil {
b.Errorf("failed to open with seed %d.", seed) b.Fatalf("failed to open with seed %d.", seed)
return
} }
} }
} }
@ -111,22 +104,19 @@ func BenchmarkDecryptionSymInvalid(b *testing.B) {
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
b.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) b.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
msg := NewSentMessage(params) msg := NewSentMessage(params)
env, err := msg.Wrap(params) env, err := msg.Wrap(params)
if err != nil { if err != nil {
b.Errorf("failed Wrap with seed %d: %s.", seed, err) b.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
f := Filter{KeySym: []byte("arbitrary stuff here")} f := Filter{KeySym: []byte("arbitrary stuff here")}
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
msg := env.Open(&f) msg := env.Open(&f)
if msg != nil { if msg != nil {
b.Errorf("opened envelope with invalid key, seed: %d.", seed) b.Fatalf("opened envelope with invalid key, seed: %d.", seed)
return
} }
} }
} }
@ -136,13 +126,11 @@ func BenchmarkDecryptionAsymValid(b *testing.B) {
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
b.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) b.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
key, err := crypto.GenerateKey() key, err := crypto.GenerateKey()
if err != nil { if err != nil {
b.Errorf("failed GenerateKey with seed %d: %s.", seed, err) b.Fatalf("failed GenerateKey with seed %d: %s.", seed, err)
return
} }
f := Filter{KeyAsym: key} f := Filter{KeyAsym: key}
params.KeySym = nil params.KeySym = nil
@ -150,15 +138,13 @@ func BenchmarkDecryptionAsymValid(b *testing.B) {
msg := NewSentMessage(params) msg := NewSentMessage(params)
env, err := msg.Wrap(params) env, err := msg.Wrap(params)
if err != nil { if err != nil {
b.Errorf("failed Wrap with seed %d: %s.", seed, err) b.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
msg := env.Open(&f) msg := env.Open(&f)
if msg == nil { if msg == nil {
b.Errorf("fail to open, seed: %d.", seed) b.Fatalf("fail to open, seed: %d.", seed)
return
} }
} }
} }
@ -168,35 +154,30 @@ func BenchmarkDecryptionAsymInvalid(b *testing.B) {
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
b.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) b.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
key, err := crypto.GenerateKey() key, err := crypto.GenerateKey()
if err != nil { if err != nil {
b.Errorf("failed GenerateKey with seed %d: %s.", seed, err) b.Fatalf("failed GenerateKey with seed %d: %s.", seed, err)
return
} }
params.KeySym = nil params.KeySym = nil
params.Dst = &key.PublicKey params.Dst = &key.PublicKey
msg := NewSentMessage(params) msg := NewSentMessage(params)
env, err := msg.Wrap(params) env, err := msg.Wrap(params)
if err != nil { if err != nil {
b.Errorf("failed Wrap with seed %d: %s.", seed, err) b.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
key, err = crypto.GenerateKey() key, err = crypto.GenerateKey()
if err != nil { if err != nil {
b.Errorf("failed GenerateKey with seed %d: %s.", seed, err) b.Fatalf("failed GenerateKey with seed %d: %s.", seed, err)
return
} }
f := Filter{KeyAsym: key} f := Filter{KeyAsym: key}
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
msg := env.Open(&f) msg := env.Open(&f)
if msg != nil { if msg != nil {
b.Errorf("opened envelope with invalid key, seed: %d.", seed) b.Fatalf("opened envelope with invalid key, seed: %d.", seed)
return
} }
} }
} }

View File

@ -46,7 +46,7 @@ const (
messagesCode = 1 messagesCode = 1
p2pCode = 2 p2pCode = 2
mailRequestCode = 3 mailRequestCode = 3
NumberOfMessageCodes = 4 NumberOfMessageCodes = 32
paddingMask = byte(3) paddingMask = byte(3)
signatureFlag = byte(4) signatureFlag = byte(4)
@ -55,6 +55,7 @@ const (
signatureLength = 65 signatureLength = 65
aesKeyLength = 32 aesKeyLength = 32
saltLength = 12 saltLength = 12
AESNonceMaxLength = 12
MaxMessageLength = 0xFFFF // todo: remove this restriction after testing in morden and analizing stats. this should be regulated by MinimumPoW. MaxMessageLength = 0xFFFF // todo: remove this restriction after testing in morden and analizing stats. this should be regulated by MinimumPoW.
MinimumPoW = 10.0 // todo: review MinimumPoW = 10.0 // todo: review

View File

@ -73,7 +73,7 @@ func NewEnvelope(ttl uint32, topic TopicType, salt []byte, aesNonce []byte, msg
} }
func (e *Envelope) IsSymmetric() bool { func (e *Envelope) IsSymmetric() bool {
return e.AESNonce != nil return len(e.AESNonce) > 0
} }
func (e *Envelope) isAsymmetric() bool { func (e *Envelope) isAsymmetric() bool {
@ -131,7 +131,7 @@ func (e *Envelope) calculatePoW(diff uint32) {
h = crypto.Keccak256(buf) h = crypto.Keccak256(buf)
firstBit := common.FirstBitSet(common.BigD(h)) firstBit := common.FirstBitSet(common.BigD(h))
x := math.Pow(2, float64(firstBit)) x := math.Pow(2, float64(firstBit))
x /= float64(len(e.Data)) x /= float64(len(e.Data)) // we only count e.Data, other variable-sized members are checked in Whisper.add()
x /= float64(e.TTL + diff) x /= float64(e.TTL + diff)
e.pow = x e.pow = x
} }

View File

@ -37,20 +37,20 @@ type Filter struct {
} }
type Filters struct { type Filters struct {
id int id uint32 // can contain any value except zero
watchers map[int]*Filter watchers map[uint32]*Filter
whisper *Whisper whisper *Whisper
mutex sync.RWMutex mutex sync.RWMutex
} }
func NewFilters(w *Whisper) *Filters { func NewFilters(w *Whisper) *Filters {
return &Filters{ return &Filters{
watchers: make(map[int]*Filter), watchers: make(map[uint32]*Filter),
whisper: w, whisper: w,
} }
} }
func (fs *Filters) Install(watcher *Filter) int { func (fs *Filters) Install(watcher *Filter) uint32 {
if watcher.Messages == nil { if watcher.Messages == nil {
watcher.Messages = make(map[common.Hash]*ReceivedMessage) watcher.Messages = make(map[common.Hash]*ReceivedMessage)
} }
@ -58,19 +58,18 @@ func (fs *Filters) Install(watcher *Filter) int {
fs.mutex.Lock() fs.mutex.Lock()
defer fs.mutex.Unlock() defer fs.mutex.Unlock()
fs.watchers[fs.id] = watcher
ret := fs.id
fs.id++ fs.id++
return ret fs.watchers[fs.id] = watcher
return fs.id
} }
func (fs *Filters) Uninstall(id int) { func (fs *Filters) Uninstall(id uint32) {
fs.mutex.Lock() fs.mutex.Lock()
defer fs.mutex.Unlock() defer fs.mutex.Unlock()
delete(fs.watchers, id) delete(fs.watchers, id)
} }
func (fs *Filters) Get(i int) *Filter { func (fs *Filters) Get(i uint32) *Filter {
fs.mutex.RLock() fs.mutex.RLock()
defer fs.mutex.RUnlock() defer fs.mutex.RUnlock()
return fs.watchers[i] return fs.watchers[i]
@ -143,18 +142,9 @@ func (f *Filter) MatchMessage(msg *ReceivedMessage) bool {
} }
if f.expectsAsymmetricEncryption() && msg.isAsymmetricEncryption() { if f.expectsAsymmetricEncryption() && msg.isAsymmetricEncryption() {
// if Dst match, ignore the topic return isPubKeyEqual(&f.KeyAsym.PublicKey, msg.Dst) && f.MatchTopic(msg.Topic)
return isPubKeyEqual(&f.KeyAsym.PublicKey, msg.Dst)
} else if f.expectsSymmetricEncryption() && msg.isSymmetricEncryption() { } else if f.expectsSymmetricEncryption() && msg.isSymmetricEncryption() {
// check if that both the key and the topic match return f.SymKeyHash == msg.SymKeyHash && f.MatchTopic(msg.Topic)
if f.SymKeyHash == msg.SymKeyHash {
for _, t := range f.Topics {
if t == msg.Topic {
return true
}
}
return false
}
} }
return false return false
} }
@ -164,25 +154,25 @@ func (f *Filter) MatchEnvelope(envelope *Envelope) bool {
return false return false
} }
encryptionMethodMatch := false
if f.expectsAsymmetricEncryption() && envelope.isAsymmetric() { if f.expectsAsymmetricEncryption() && envelope.isAsymmetric() {
encryptionMethodMatch = true return f.MatchTopic(envelope.Topic)
if f.Topics == nil {
// wildcard
return true
}
} else if f.expectsSymmetricEncryption() && envelope.IsSymmetric() { } else if f.expectsSymmetricEncryption() && envelope.IsSymmetric() {
encryptionMethodMatch = true return f.MatchTopic(envelope.Topic)
}
return false
}
func (f *Filter) MatchTopic(topic TopicType) bool {
if len(f.Topics) == 0 {
// any topic matches
return true
} }
if encryptionMethodMatch {
for _, t := range f.Topics { for _, t := range f.Topics {
if t == envelope.Topic { if t == topic {
return true return true
} }
} }
}
return false return false
} }

View File

@ -43,12 +43,12 @@ func InitDebugTest(i int64) {
type FilterTestCase struct { type FilterTestCase struct {
f *Filter f *Filter
id int id uint32
alive bool alive bool
msgCnt int msgCnt int
} }
func generateFilter(x *testing.T, symmetric bool) (*Filter, error) { func generateFilter(t *testing.T, symmetric bool) (*Filter, error) {
var f Filter var f Filter
f.Messages = make(map[common.Hash]*ReceivedMessage) f.Messages = make(map[common.Hash]*ReceivedMessage)
@ -61,7 +61,7 @@ func generateFilter(x *testing.T, symmetric bool) (*Filter, error) {
key, err := crypto.GenerateKey() key, err := crypto.GenerateKey()
if err != nil { if err != nil {
x.Errorf("generateFilter failed 1 with seed %d.", seed) t.Fatalf("generateFilter 1 failed with seed %d.", seed)
return nil, err return nil, err
} }
f.Src = &key.PublicKey f.Src = &key.PublicKey
@ -73,7 +73,7 @@ func generateFilter(x *testing.T, symmetric bool) (*Filter, error) {
} else { } else {
f.KeyAsym, err = crypto.GenerateKey() f.KeyAsym, err = crypto.GenerateKey()
if err != nil { if err != nil {
x.Errorf("generateFilter failed 2 with seed %d.", seed) t.Fatalf("generateFilter 2 failed with seed %d.", seed)
return nil, err return nil, err
} }
} }
@ -82,105 +82,94 @@ func generateFilter(x *testing.T, symmetric bool) (*Filter, error) {
return &f, nil return &f, nil
} }
func generateTestCases(x *testing.T, SizeTestFilters int) []FilterTestCase { func generateTestCases(t *testing.T, SizeTestFilters int) []FilterTestCase {
cases := make([]FilterTestCase, SizeTestFilters) cases := make([]FilterTestCase, SizeTestFilters)
for i := 0; i < SizeTestFilters; i++ { for i := 0; i < SizeTestFilters; i++ {
f, _ := generateFilter(x, true) f, _ := generateFilter(t, true)
cases[i].f = f cases[i].f = f
cases[i].alive = (rand.Int()&int(1) == 0) cases[i].alive = (rand.Int()&int(1) == 0)
} }
return cases return cases
} }
func TestInstallFilters(x *testing.T) { func TestInstallFilters(t *testing.T) {
InitSingleTest() InitSingleTest()
const SizeTestFilters = 256 const SizeTestFilters = 256
w := NewWhisper(nil) w := NewWhisper(nil)
filters := NewFilters(w) filters := NewFilters(w)
tst := generateTestCases(x, SizeTestFilters) tst := generateTestCases(t, SizeTestFilters)
var j int var j uint32
for i := 0; i < SizeTestFilters; i++ { for i := 0; i < SizeTestFilters; i++ {
j = filters.Install(tst[i].f) j = filters.Install(tst[i].f)
tst[i].id = j tst[i].id = j
} }
if j < SizeTestFilters-1 { if j < SizeTestFilters-1 {
x.Errorf("seed %d: wrong index %d", seed, j) t.Fatalf("seed %d: wrong index %d", seed, j)
return
} }
for _, t := range tst { for _, testCase := range tst {
if !t.alive { if !testCase.alive {
filters.Uninstall(t.id) filters.Uninstall(testCase.id)
} }
} }
for i, t := range tst { for i, testCase := range tst {
fil := filters.Get(t.id) fil := filters.Get(testCase.id)
exist := (fil != nil) exist := (fil != nil)
if exist != t.alive { if exist != testCase.alive {
x.Errorf("seed %d: failed alive: %d, %v, %v", seed, i, exist, t.alive) t.Fatalf("seed %d: failed alive: %d, %v, %v", seed, i, exist, testCase.alive)
return
} }
if exist && fil.PoW != t.f.PoW { if exist && fil.PoW != testCase.f.PoW {
x.Errorf("seed %d: failed Get: %d, %v, %v", seed, i, exist, t.alive) t.Fatalf("seed %d: failed Get: %d, %v, %v", seed, i, exist, testCase.alive)
return
} }
} }
} }
func TestComparePubKey(x *testing.T) { func TestComparePubKey(t *testing.T) {
InitSingleTest() InitSingleTest()
key1, err := crypto.GenerateKey() key1, err := crypto.GenerateKey()
if err != nil { if err != nil {
x.Errorf("failed GenerateKey 1 with seed %d: %s.", seed, err) t.Fatalf("failed to generate first key with seed %d: %s.", seed, err)
return
} }
key2, err := crypto.GenerateKey() key2, err := crypto.GenerateKey()
if err != nil { if err != nil {
x.Errorf("failed GenerateKey 2 with seed %d: %s.", seed, err) t.Fatalf("failed to generate second key with seed %d: %s.", seed, err)
return
} }
if isPubKeyEqual(&key1.PublicKey, &key2.PublicKey) { if isPubKeyEqual(&key1.PublicKey, &key2.PublicKey) {
x.Errorf("failed !equal with seed %d.", seed) t.Fatalf("public keys are equal, seed %d.", seed)
return
} }
// generate key3 == key1 // generate key3 == key1
rand.Seed(seed) rand.Seed(seed)
key3, err := crypto.GenerateKey() key3, err := crypto.GenerateKey()
if err != nil { if err != nil {
x.Errorf("failed GenerateKey 3 with seed %d: %s.", seed, err) t.Fatalf("failed to generate third key with seed %d: %s.", seed, err)
return
} }
if isPubKeyEqual(&key1.PublicKey, &key3.PublicKey) { if isPubKeyEqual(&key1.PublicKey, &key3.PublicKey) {
x.Errorf("failed equal with seed %d.", seed) t.Fatalf("key1 == key3, seed %d.", seed)
return
} }
} }
func TestMatchEnvelope(x *testing.T) { func TestMatchEnvelope(t *testing.T) {
InitSingleTest() InitSingleTest()
fsym, err := generateFilter(x, true) fsym, err := generateFilter(t, true)
if err != nil { if err != nil {
x.Errorf("failed generateFilter 1 with seed %d: %s.", seed, err) t.Fatalf("failed generateFilter with seed %d: %s.", seed, err)
return
} }
fasym, err := generateFilter(x, false) fasym, err := generateFilter(t, false)
if err != nil { if err != nil {
x.Errorf("failed generateFilter 2 with seed %d: %s.", seed, err) t.Fatalf("failed generateFilter() with seed %d: %s.", seed, err)
return
} }
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
x.Errorf("failed generateMessageParams 3 with seed %d: %s.", seed, err) t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
params.Topic[0] = 0xFF // ensure mismatch params.Topic[0] = 0xFF // ensure mismatch
@ -189,18 +178,15 @@ func TestMatchEnvelope(x *testing.T) {
msg := NewSentMessage(params) msg := NewSentMessage(params)
env, err := msg.Wrap(params) env, err := msg.Wrap(params)
if err != nil { if err != nil {
x.Errorf("failed Wrap 4 with seed %d: %s.", seed, err) t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
match := fsym.MatchEnvelope(env) match := fsym.MatchEnvelope(env)
if match { if match {
x.Errorf("failed test case 5 with seed %d.", seed) t.Fatalf("failed MatchEnvelope symmetric with seed %d.", seed)
return
} }
match = fasym.MatchEnvelope(env) match = fasym.MatchEnvelope(env)
if match { if match {
x.Errorf("failed test case 6 with seed %d.", seed) t.Fatalf("failed MatchEnvelope asymmetric with seed %d.", seed)
return
} }
// encrypt symmetrically // encrypt symmetrically
@ -210,125 +196,123 @@ func TestMatchEnvelope(x *testing.T) {
msg = NewSentMessage(params) msg = NewSentMessage(params)
env, err = msg.Wrap(params) env, err = msg.Wrap(params)
if err != nil { if err != nil {
x.Errorf("failed test case 7 with seed %d, test case 3: %s.", seed, err) t.Fatalf("failed Wrap() with seed %d: %s.", seed, err)
return
} }
// symmetric + matching topic: match // symmetric + matching topic: match
match = fsym.MatchEnvelope(env) match = fsym.MatchEnvelope(env)
if !match { if !match {
x.Errorf("failed test case 8 with seed %d.", seed) t.Fatalf("failed MatchEnvelope() symmetric with seed %d.", seed)
return
} }
// asymmetric + matching topic: mismatch // asymmetric + matching topic: mismatch
match = fasym.MatchEnvelope(env) match = fasym.MatchEnvelope(env)
if match { if match {
x.Errorf("failed test case 9 with seed %d.", seed) t.Fatalf("failed MatchEnvelope() asymmetric with seed %d.", seed)
return
} }
// symmetric + matching topic + insufficient PoW: mismatch // symmetric + matching topic + insufficient PoW: mismatch
fsym.PoW = env.PoW() + 1.0 fsym.PoW = env.PoW() + 1.0
match = fsym.MatchEnvelope(env) match = fsym.MatchEnvelope(env)
if match { if match {
x.Errorf("failed test case 10 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(symmetric + matching topic + insufficient PoW) asymmetric with seed %d.", seed)
return
} }
// symmetric + matching topic + sufficient PoW: match // symmetric + matching topic + sufficient PoW: match
fsym.PoW = env.PoW() / 2 fsym.PoW = env.PoW() / 2
match = fsym.MatchEnvelope(env) match = fsym.MatchEnvelope(env)
if !match { if !match {
x.Errorf("failed test case 11 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(symmetric + matching topic + sufficient PoW) with seed %d.", seed)
return
} }
// symmetric + topics are nil: mismatch // symmetric + topics are nil (wildcard): match
prevTopics := fsym.Topics prevTopics := fsym.Topics
fsym.Topics = nil fsym.Topics = nil
match = fasym.MatchEnvelope(env) match = fsym.MatchEnvelope(env)
if match { if !match {
x.Errorf("failed test case 12 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(symmetric + topics are nil) with seed %d.", seed)
return
} }
fsym.Topics = prevTopics fsym.Topics = prevTopics
// encrypt asymmetrically // encrypt asymmetrically
key, err := crypto.GenerateKey() key, err := crypto.GenerateKey()
if err != nil { if err != nil {
x.Errorf("failed GenerateKey 13 with seed %d: %s.", seed, err) t.Fatalf("failed GenerateKey with seed %d: %s.", seed, err)
return
} }
params.KeySym = nil params.KeySym = nil
params.Dst = &key.PublicKey params.Dst = &key.PublicKey
msg = NewSentMessage(params) msg = NewSentMessage(params)
env, err = msg.Wrap(params) env, err = msg.Wrap(params)
if err != nil { if err != nil {
x.Errorf("failed test case 14 with seed %d, test case 3: %s.", seed, err) t.Fatalf("failed Wrap() with seed %d: %s.", seed, err)
return
} }
// encryption method mismatch // encryption method mismatch
match = fsym.MatchEnvelope(env) match = fsym.MatchEnvelope(env)
if match { if match {
x.Errorf("failed test case 15 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(encryption method mismatch) with seed %d.", seed)
return
} }
// asymmetric + mismatching topic: mismatch // asymmetric + mismatching topic: mismatch
match = fasym.MatchEnvelope(env) match = fasym.MatchEnvelope(env)
if !match { if !match {
x.Errorf("failed test case 16 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(asymmetric + mismatching topic) with seed %d.", seed)
return
} }
// asymmetric + matching topic: match // asymmetric + matching topic: match
fasym.Topics[i] = fasym.Topics[i+1] fasym.Topics[i] = fasym.Topics[i+1]
match = fasym.MatchEnvelope(env) match = fasym.MatchEnvelope(env)
if match { if match {
x.Errorf("failed test case 17 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(asymmetric + matching topic) with seed %d.", seed)
return
} }
// asymmetric + topic is nil (wildcard): match // asymmetric + filter without topic (wildcard): match
fasym.Topics = nil fasym.Topics = nil
match = fasym.MatchEnvelope(env) match = fasym.MatchEnvelope(env)
if !match { if !match {
x.Errorf("failed test case 18 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(asymmetric + filter without topic) with seed %d.", seed)
return
} }
// asymmetric + insufficient PoW: mismatch // asymmetric + insufficient PoW: mismatch
fasym.PoW = env.PoW() + 1.0 fasym.PoW = env.PoW() + 1.0
match = fasym.MatchEnvelope(env) match = fasym.MatchEnvelope(env)
if match { if match {
x.Errorf("failed test case 19 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(asymmetric + insufficient PoW) with seed %d.", seed)
return
} }
// asymmetric + sufficient PoW: match // asymmetric + sufficient PoW: match
fasym.PoW = env.PoW() / 2 fasym.PoW = env.PoW() / 2
match = fasym.MatchEnvelope(env) match = fasym.MatchEnvelope(env)
if !match { if !match {
x.Errorf("failed test case 20 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(asymmetric + sufficient PoW) with seed %d.", seed)
return }
// filter without topic + envelope without topic: match
env.Topic = TopicType{}
match = fasym.MatchEnvelope(env)
if !match {
t.Fatalf("failed MatchEnvelope(filter without topic + envelope without topic) with seed %d.", seed)
}
// filter with topic + envelope without topic: mismatch
fasym.Topics = fsym.Topics
match = fasym.MatchEnvelope(env)
if match {
t.Fatalf("failed MatchEnvelope(filter without topic + envelope without topic) with seed %d.", seed)
} }
} }
func TestMatchMessageSym(x *testing.T) { func TestMatchMessageSym(t *testing.T) {
InitSingleTest() InitSingleTest()
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
x.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
f, err := generateFilter(x, true) f, err := generateFilter(t, true)
if err != nil { if err != nil {
x.Errorf("failed generateFilter 1 with seed %d: %s.", seed, err) t.Fatalf("failed generateFilter with seed %d: %s.", seed, err)
return
} }
const index = 1 const index = 1
@ -338,106 +322,91 @@ func TestMatchMessageSym(x *testing.T) {
sentMessage := NewSentMessage(params) sentMessage := NewSentMessage(params)
env, err := sentMessage.Wrap(params) env, err := sentMessage.Wrap(params)
if err != nil { if err != nil {
x.Errorf("failed Wrap 2 with seed %d: %s.", seed, err) t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
msg := env.Open(f) msg := env.Open(f)
if msg == nil { if msg == nil {
x.Errorf("failed to open 3 with seed %d.", seed) t.Fatalf("failed Open with seed %d.", seed)
return
} }
// Src mismatch // Src mismatch
if f.MatchMessage(msg) { if f.MatchMessage(msg) {
x.Errorf("failed test case 4 with seed %d.", seed) t.Fatalf("failed MatchMessage(src mismatch) with seed %d.", seed)
return
} }
// Src: match // Src: match
*f.Src.X = *params.Src.PublicKey.X *f.Src.X = *params.Src.PublicKey.X
*f.Src.Y = *params.Src.PublicKey.Y *f.Src.Y = *params.Src.PublicKey.Y
if !f.MatchMessage(msg) { if !f.MatchMessage(msg) {
x.Errorf("failed test case 5 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(src match) with seed %d.", seed)
return
} }
// insufficient PoW: mismatch // insufficient PoW: mismatch
f.PoW = msg.PoW + 1.0 f.PoW = msg.PoW + 1.0
if f.MatchMessage(msg) { if f.MatchMessage(msg) {
x.Errorf("failed test case 6 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(insufficient PoW) with seed %d.", seed)
return
} }
// sufficient PoW: match // sufficient PoW: match
f.PoW = msg.PoW / 2 f.PoW = msg.PoW / 2
if !f.MatchMessage(msg) { if !f.MatchMessage(msg) {
x.Errorf("failed test case 7 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(sufficient PoW) with seed %d.", seed)
return
} }
// topic mismatch // topic mismatch
f.Topics[index][0]++ f.Topics[index][0]++
if f.MatchMessage(msg) { if f.MatchMessage(msg) {
x.Errorf("failed test case 8 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(topic mismatch) with seed %d.", seed)
return
} }
f.Topics[index][0]-- f.Topics[index][0]--
// key mismatch // key mismatch
f.SymKeyHash[0]++ f.SymKeyHash[0]++
if f.MatchMessage(msg) { if f.MatchMessage(msg) {
x.Errorf("failed test case 9 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(key mismatch) with seed %d.", seed)
return
} }
f.SymKeyHash[0]-- f.SymKeyHash[0]--
// Src absent: match // Src absent: match
f.Src = nil f.Src = nil
if !f.MatchMessage(msg) { if !f.MatchMessage(msg) {
x.Errorf("failed test case 10 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(src absent) with seed %d.", seed)
return
} }
// key hash mismatch mismatch // key hash mismatch
h := f.SymKeyHash h := f.SymKeyHash
f.SymKeyHash = common.Hash{} f.SymKeyHash = common.Hash{}
if f.MatchMessage(msg) { if f.MatchMessage(msg) {
x.Errorf("failed test case 11 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(key hash mismatch) with seed %d.", seed)
return
} }
f.SymKeyHash = h f.SymKeyHash = h
if !f.MatchMessage(msg) { if !f.MatchMessage(msg) {
x.Errorf("failed test case 12 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(key hash match) with seed %d.", seed)
return
} }
// encryption method mismatch // encryption method mismatch
f.KeySym = nil f.KeySym = nil
f.KeyAsym, err = crypto.GenerateKey() f.KeyAsym, err = crypto.GenerateKey()
if err != nil { if err != nil {
x.Errorf("failed GenerateKey 13 with seed %d: %s.", seed, err) t.Fatalf("failed GenerateKey with seed %d: %s.", seed, err)
return
} }
if f.MatchMessage(msg) { if f.MatchMessage(msg) {
x.Errorf("failed test case 14 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(encryption method mismatch) with seed %d.", seed)
return
} }
} }
func TestMatchMessageAsym(x *testing.T) { func TestMatchMessageAsym(t *testing.T) {
InitSingleTest() InitSingleTest()
f, err := generateFilter(x, false) f, err := generateFilter(t, false)
if err != nil { if err != nil {
x.Errorf("failed generateFilter with seed %d: %s.", seed, err) t.Fatalf("failed generateFilter with seed %d: %s.", seed, err)
return
} }
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
x.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
const index = 1 const index = 1
@ -449,50 +418,42 @@ func TestMatchMessageAsym(x *testing.T) {
sentMessage := NewSentMessage(params) sentMessage := NewSentMessage(params)
env, err := sentMessage.Wrap(params) env, err := sentMessage.Wrap(params)
if err != nil { if err != nil {
x.Errorf("failed Wrap with seed %d: %s.", seed, err) t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
msg := env.Open(f) msg := env.Open(f)
if msg == nil { if msg == nil {
x.Errorf("failed to open with seed %d.", seed) t.Fatalf("failed to open with seed %d.", seed)
return
} }
// Src mismatch // Src mismatch
if f.MatchMessage(msg) { if f.MatchMessage(msg) {
x.Errorf("failed test case 4 with seed %d.", seed) t.Fatalf("failed MatchMessage(src mismatch) with seed %d.", seed)
return
} }
// Src: match // Src: match
*f.Src.X = *params.Src.PublicKey.X *f.Src.X = *params.Src.PublicKey.X
*f.Src.Y = *params.Src.PublicKey.Y *f.Src.Y = *params.Src.PublicKey.Y
if !f.MatchMessage(msg) { if !f.MatchMessage(msg) {
x.Errorf("failed test case 5 with seed %d.", seed) t.Fatalf("failed MatchMessage(src match) with seed %d.", seed)
return
} }
// insufficient PoW: mismatch // insufficient PoW: mismatch
f.PoW = msg.PoW + 1.0 f.PoW = msg.PoW + 1.0
if f.MatchMessage(msg) { if f.MatchMessage(msg) {
x.Errorf("failed test case 6 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(insufficient PoW) with seed %d.", seed)
return
} }
// sufficient PoW: match // sufficient PoW: match
f.PoW = msg.PoW / 2 f.PoW = msg.PoW / 2
if !f.MatchMessage(msg) { if !f.MatchMessage(msg) {
x.Errorf("failed test case 7 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(sufficient PoW) with seed %d.", seed)
return
} }
// topic mismatch, but still match, because for asymmetric encryption // topic mismatch
// only private key matters (in case the message is already decrypted)
f.Topics[index][0]++ f.Topics[index][0]++
if !f.MatchMessage(msg) { if f.MatchMessage(msg) {
x.Errorf("failed test case 8 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(topic mismatch) with seed %d.", seed)
return
} }
f.Topics[index][0]-- f.Topics[index][0]--
@ -501,24 +462,21 @@ func TestMatchMessageAsym(x *testing.T) {
zero := *big.NewInt(0) zero := *big.NewInt(0)
*f.KeyAsym.PublicKey.X = zero *f.KeyAsym.PublicKey.X = zero
if f.MatchMessage(msg) { if f.MatchMessage(msg) {
x.Errorf("failed test case 9 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(key mismatch) with seed %d.", seed)
return
} }
*f.KeyAsym.PublicKey.X = prev *f.KeyAsym.PublicKey.X = prev
// Src absent: match // Src absent: match
f.Src = nil f.Src = nil
if !f.MatchMessage(msg) { if !f.MatchMessage(msg) {
x.Errorf("failed test case 10 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(src absent) with seed %d.", seed)
return
} }
// encryption method mismatch // encryption method mismatch
f.KeySym = keySymOrig f.KeySym = keySymOrig
f.KeyAsym = nil f.KeyAsym = nil
if f.MatchMessage(msg) { if f.MatchMessage(msg) {
x.Errorf("failed test case 11 with seed %d.", seed) t.Fatalf("failed MatchEnvelope(encryption method mismatch) with seed %d.", seed)
return
} }
} }
@ -535,10 +493,10 @@ func cloneFilter(orig *Filter) *Filter {
return &clone return &clone
} }
func generateCompatibeEnvelope(x *testing.T, f *Filter) *Envelope { func generateCompatibeEnvelope(t *testing.T, f *Filter) *Envelope {
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
x.Errorf("failed generateMessageParams 77 with seed %d: %s.", seed, err) t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return nil return nil
} }
@ -547,23 +505,24 @@ func generateCompatibeEnvelope(x *testing.T, f *Filter) *Envelope {
sentMessage := NewSentMessage(params) sentMessage := NewSentMessage(params)
env, err := sentMessage.Wrap(params) env, err := sentMessage.Wrap(params)
if err != nil { if err != nil {
x.Errorf("failed Wrap 78 with seed %d: %s.", seed, err) t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return nil return nil
} }
return env return env
} }
func TestWatchers(x *testing.T) { func TestWatchers(t *testing.T) {
InitSingleTest() InitSingleTest()
const NumFilters = 16 const NumFilters = 16
const NumMessages = 256 const NumMessages = 256
var i, j int var i int
var j uint32
var e *Envelope var e *Envelope
w := NewWhisper(nil) w := NewWhisper(nil)
filters := NewFilters(w) filters := NewFilters(w)
tst := generateTestCases(x, NumFilters) tst := generateTestCases(t, NumFilters)
for i = 0; i < NumFilters; i++ { for i = 0; i < NumFilters; i++ {
tst[i].f.Src = nil tst[i].f.Src = nil
j = filters.Install(tst[i].f) j = filters.Install(tst[i].f)
@ -574,8 +533,8 @@ func TestWatchers(x *testing.T) {
var envelopes [NumMessages]*Envelope var envelopes [NumMessages]*Envelope
for i = 0; i < NumMessages; i++ { for i = 0; i < NumMessages; i++ {
j = rand.Int() % NumFilters j = rand.Uint32() % NumFilters
e = generateCompatibeEnvelope(x, tst[j].f) e = generateCompatibeEnvelope(t, tst[j].f)
envelopes[i] = e envelopes[i] = e
tst[j].msgCnt++ tst[j].msgCnt++
} }
@ -595,20 +554,17 @@ func TestWatchers(x *testing.T) {
} }
if total != NumMessages { if total != NumMessages {
x.Errorf("failed test case 1 with seed %d: total = %d, want: %d.", seed, total, NumMessages) t.Fatalf("failed with seed %d: total = %d, want: %d.", seed, total, NumMessages)
return
} }
for i = 0; i < NumFilters; i++ { for i = 0; i < NumFilters; i++ {
mail = tst[i].f.Retrieve() mail = tst[i].f.Retrieve()
if len(mail) != 0 { if len(mail) != 0 {
x.Errorf("failed test case 2 with seed %d: i = %d.", seed, i) t.Fatalf("failed with seed %d: i = %d.", seed, i)
return
} }
if tst[i].msgCnt != count[i] { if tst[i].msgCnt != count[i] {
x.Errorf("failed test case 3 with seed %d: i = %d, get %d, want %d.", seed, i, tst[i].msgCnt, count[i]) t.Fatalf("failed with seed %d: count[%d]: get %d, want %d.", seed, i, tst[i].msgCnt, count[i])
return
} }
} }
@ -626,12 +582,12 @@ func TestWatchers(x *testing.T) {
} }
// make sure that the first watcher receives at least one message // make sure that the first watcher receives at least one message
e = generateCompatibeEnvelope(x, tst[0].f) e = generateCompatibeEnvelope(t, tst[0].f)
envelopes[0] = e envelopes[0] = e
tst[0].msgCnt++ tst[0].msgCnt++
for i = 1; i < NumMessages; i++ { for i = 1; i < NumMessages; i++ {
j = rand.Int() % NumFilters j = rand.Uint32() % NumFilters
e = generateCompatibeEnvelope(x, tst[j].f) e = generateCompatibeEnvelope(t, tst[j].f)
envelopes[i] = e envelopes[i] = e
tst[j].msgCnt++ tst[j].msgCnt++
} }
@ -648,30 +604,25 @@ func TestWatchers(x *testing.T) {
combined := tst[0].msgCnt + tst[last].msgCnt combined := tst[0].msgCnt + tst[last].msgCnt
if total != NumMessages+count[0] { if total != NumMessages+count[0] {
x.Errorf("failed test case 4 with seed %d: total = %d, count[0] = %d.", seed, total, count[0]) t.Fatalf("failed with seed %d: total = %d, count[0] = %d.", seed, total, count[0])
return
} }
if combined != count[0] { if combined != count[0] {
x.Errorf("failed test case 5 with seed %d: combined = %d, count[0] = %d.", seed, combined, count[0]) t.Fatalf("failed with seed %d: combined = %d, count[0] = %d.", seed, combined, count[0])
return
} }
if combined != count[last] { if combined != count[last] {
x.Errorf("failed test case 6 with seed %d: combined = %d, count[last] = %d.", seed, combined, count[last]) t.Fatalf("failed with seed %d: combined = %d, count[last] = %d.", seed, combined, count[last])
return
} }
for i = 1; i < NumFilters-1; i++ { for i = 1; i < NumFilters-1; i++ {
mail = tst[i].f.Retrieve() mail = tst[i].f.Retrieve()
if len(mail) != 0 { if len(mail) != 0 {
x.Errorf("failed test case 7 with seed %d: i = %d.", seed, i) t.Fatalf("failed with seed %d: i = %d.", seed, i)
return
} }
if tst[i].msgCnt != count[i] { if tst[i].msgCnt != count[i] {
x.Errorf("failed test case 8 with seed %d: i = %d, get %d, want %d.", seed, i, tst[i].msgCnt, count[i]) t.Fatalf("failed with seed %d: i = %d, get %d, want %d.", seed, i, tst[i].msgCnt, count[i])
return
} }
} }
@ -686,11 +637,13 @@ func TestWatchers(x *testing.T) {
} }
if total != 0 { if total != 0 {
x.Errorf("failed test case 9 with seed %d.", seed) t.Fatalf("failed with seed %d: total: got %d, want 0.", seed, total)
return
} }
f := filters.Get(0) f := filters.Get(1)
if f == nil {
t.Fatalf("failed to get the filter with seed %d.", seed)
}
f.AcceptP2P = true f.AcceptP2P = true
total = 0 total = 0
filters.NotifyWatchers(envelopes[0], p2pCode) filters.NotifyWatchers(envelopes[0], p2pCode)
@ -701,7 +654,6 @@ func TestWatchers(x *testing.T) {
} }
if total != 1 { if total != 1 {
x.Errorf("failed test case 10 with seed %d: total = %d.", seed, total) t.Fatalf("failed with seed %d: total: got %d, want 1.", seed, total)
return
} }
} }

View File

@ -130,7 +130,7 @@ func (msg *SentMessage) appendPadding(params *MessageParams) {
panic("please fix the padding algorithm before releasing new version") panic("please fix the padding algorithm before releasing new version")
} }
buf := make([]byte, padSize) buf := make([]byte, padSize)
randomize(buf[1:]) // change to: err = mrand.Read(buf[1:]) randomize(buf[1:])
buf[0] = byte(padSize) buf[0] = byte(padSize)
if params.Padding != nil { if params.Padding != nil {
copy(buf[1:], params.Padding) copy(buf[1:], params.Padding)
@ -208,7 +208,10 @@ func (msg *SentMessage) encryptSymmetric(key []byte) (salt []byte, nonce []byte,
_, err = crand.Read(nonce) _, err = crand.Read(nonce)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} else if !validateSymmetricKey(nonce) {
return nil, nil, errors.New("crypto/rand failed to generate nonce")
} }
msg.Raw = aesgcm.Seal(nil, nonce, msg.Raw, nil) msg.Raw = aesgcm.Seal(nil, nonce, msg.Raw, nil)
return salt, nonce, nil return salt, nonce, nil
} }

View File

@ -57,17 +57,15 @@ func generateMessageParams() (*MessageParams, error) {
return &p, nil return &p, nil
} }
func singleMessageTest(x *testing.T, symmetric bool) { func singleMessageTest(t *testing.T, symmetric bool) {
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
x.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
key, err := crypto.GenerateKey() key, err := crypto.GenerateKey()
if err != nil { if err != nil {
x.Errorf("failed GenerateKey with seed %d: %s.", seed, err) t.Fatalf("failed GenerateKey with seed %d: %s.", seed, err)
return
} }
if !symmetric { if !symmetric {
@ -85,8 +83,7 @@ func singleMessageTest(x *testing.T, symmetric bool) {
msg := NewSentMessage(params) msg := NewSentMessage(params)
env, err := msg.Wrap(params) env, err := msg.Wrap(params)
if err != nil { if err != nil {
x.Errorf("failed Wrap with seed %d: %s.", seed, err) t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
var decrypted *ReceivedMessage var decrypted *ReceivedMessage
@ -97,57 +94,49 @@ func singleMessageTest(x *testing.T, symmetric bool) {
} }
if err != nil { if err != nil {
x.Errorf("failed to encrypt with seed %d: %s.", seed, err) t.Fatalf("failed to encrypt with seed %d: %s.", seed, err)
return
} }
if !decrypted.Validate() { if !decrypted.Validate() {
x.Errorf("failed to validate with seed %d.", seed) t.Fatalf("failed to validate with seed %d.", seed)
return
} }
padsz := len(decrypted.Padding) padsz := len(decrypted.Padding)
if bytes.Compare(steg[:padsz], decrypted.Padding) != 0 { if bytes.Compare(steg[:padsz], decrypted.Padding) != 0 {
x.Errorf("failed with seed %d: compare padding.", seed) t.Fatalf("failed with seed %d: compare padding.", seed)
return
} }
if bytes.Compare(text, decrypted.Payload) != 0 { if bytes.Compare(text, decrypted.Payload) != 0 {
x.Errorf("failed with seed %d: compare payload.", seed) t.Fatalf("failed with seed %d: compare payload.", seed)
return
} }
if !isMessageSigned(decrypted.Raw[0]) { if !isMessageSigned(decrypted.Raw[0]) {
x.Errorf("failed with seed %d: unsigned.", seed) t.Fatalf("failed with seed %d: unsigned.", seed)
return
} }
if len(decrypted.Signature) != signatureLength { if len(decrypted.Signature) != signatureLength {
x.Errorf("failed with seed %d: signature len %d.", seed, len(decrypted.Signature)) t.Fatalf("failed with seed %d: signature len %d.", seed, len(decrypted.Signature))
return
} }
if !isPubKeyEqual(decrypted.Src, &params.Src.PublicKey) { if !isPubKeyEqual(decrypted.Src, &params.Src.PublicKey) {
x.Errorf("failed with seed %d: signature mismatch.", seed) t.Fatalf("failed with seed %d: signature mismatch.", seed)
return
} }
} }
func TestMessageEncryption(x *testing.T) { func TestMessageEncryption(t *testing.T) {
InitSingleTest() InitSingleTest()
var symmetric bool var symmetric bool
for i := 0; i < 256; i++ { for i := 0; i < 256; i++ {
singleMessageTest(x, symmetric) singleMessageTest(t, symmetric)
symmetric = !symmetric symmetric = !symmetric
} }
} }
func TestMessageWrap(x *testing.T) { func TestMessageWrap(t *testing.T) {
seed = int64(1777444222) seed = int64(1777444222)
rand.Seed(seed) rand.Seed(seed)
target := 128.0 target := 128.0
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
x.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
msg := NewSentMessage(params) msg := NewSentMessage(params)
@ -156,26 +145,23 @@ func TestMessageWrap(x *testing.T) {
params.PoW = target params.PoW = target
env, err := msg.Wrap(params) env, err := msg.Wrap(params)
if err != nil { if err != nil {
x.Errorf("failed Wrap with seed %d: %s.", seed, err) t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
pow := env.PoW() pow := env.PoW()
if pow < target { if pow < target {
x.Errorf("failed Wrap with seed %d: pow < target (%f vs. %f).", seed, pow, target) t.Fatalf("failed Wrap with seed %d: pow < target (%f vs. %f).", seed, pow, target)
return
} }
} }
func TestMessageSeal(x *testing.T) { func TestMessageSeal(t *testing.T) {
// this test depends on deterministic choice of seed (1976726903) // this test depends on deterministic choice of seed (1976726903)
seed = int64(1976726903) seed = int64(1976726903)
rand.Seed(seed) rand.Seed(seed)
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
x.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
msg := NewSentMessage(params) msg := NewSentMessage(params)
@ -187,8 +173,7 @@ func TestMessageSeal(x *testing.T) {
env := NewEnvelope(params.TTL, params.Topic, salt, aesnonce, msg) env := NewEnvelope(params.TTL, params.Topic, salt, aesnonce, msg)
if err != nil { if err != nil {
x.Errorf("failed Wrap with seed %d: %s.", seed, err) t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
env.Expiry = uint32(seed) // make it deterministic env.Expiry = uint32(seed) // make it deterministic
@ -200,8 +185,7 @@ func TestMessageSeal(x *testing.T) {
env.calculatePoW(0) env.calculatePoW(0)
pow := env.PoW() pow := env.PoW()
if pow < target { if pow < target {
x.Errorf("failed Wrap with seed %d: pow < target (%f vs. %f).", seed, pow, target) t.Fatalf("failed Wrap with seed %d: pow < target (%f vs. %f).", seed, pow, target)
return
} }
params.WorkTime = 1 params.WorkTime = 1
@ -210,32 +194,29 @@ func TestMessageSeal(x *testing.T) {
env.calculatePoW(0) env.calculatePoW(0)
pow = env.PoW() pow = env.PoW()
if pow < 2*target { if pow < 2*target {
x.Errorf("failed Wrap with seed %d: pow too small %f.", seed, pow) t.Fatalf("failed Wrap with seed %d: pow too small %f.", seed, pow)
return
} }
} }
func TestEnvelopeOpen(x *testing.T) { func TestEnvelopeOpen(t *testing.T) {
InitSingleTest() InitSingleTest()
var symmetric bool var symmetric bool
for i := 0; i < 256; i++ { for i := 0; i < 256; i++ {
singleEnvelopeOpenTest(x, symmetric) singleEnvelopeOpenTest(t, symmetric)
symmetric = !symmetric symmetric = !symmetric
} }
} }
func singleEnvelopeOpenTest(x *testing.T, symmetric bool) { func singleEnvelopeOpenTest(t *testing.T, symmetric bool) {
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
x.Errorf("failed generateMessageParams with seed %d: %s.", seed, err) t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
return
} }
key, err := crypto.GenerateKey() key, err := crypto.GenerateKey()
if err != nil { if err != nil {
x.Errorf("failed GenerateKey with seed %d: %s.", seed, err) t.Fatalf("failed GenerateKey with seed %d: %s.", seed, err)
return
} }
if !symmetric { if !symmetric {
@ -253,54 +234,43 @@ func singleEnvelopeOpenTest(x *testing.T, symmetric bool) {
msg := NewSentMessage(params) msg := NewSentMessage(params)
env, err := msg.Wrap(params) env, err := msg.Wrap(params)
if err != nil { if err != nil {
x.Errorf("failed Wrap with seed %d: %s.", seed, err) t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
return
} }
f := Filter{KeyAsym: key, KeySym: params.KeySym} f := Filter{KeyAsym: key, KeySym: params.KeySym}
decrypted := env.Open(&f) decrypted := env.Open(&f)
if decrypted == nil { if decrypted == nil {
x.Errorf("failed to open with seed %d.", seed) t.Fatalf("failed to open with seed %d.", seed)
return
} }
padsz := len(decrypted.Padding) padsz := len(decrypted.Padding)
if bytes.Compare(steg[:padsz], decrypted.Padding) != 0 { if bytes.Compare(steg[:padsz], decrypted.Padding) != 0 {
x.Errorf("failed with seed %d: compare padding.", seed) t.Fatalf("failed with seed %d: compare padding.", seed)
return
} }
if bytes.Compare(text, decrypted.Payload) != 0 { if bytes.Compare(text, decrypted.Payload) != 0 {
x.Errorf("failed with seed %d: compare payload.", seed) t.Fatalf("failed with seed %d: compare payload.", seed)
return
} }
if !isMessageSigned(decrypted.Raw[0]) { if !isMessageSigned(decrypted.Raw[0]) {
x.Errorf("failed with seed %d: unsigned.", seed) t.Fatalf("failed with seed %d: unsigned.", seed)
return
} }
if len(decrypted.Signature) != signatureLength { if len(decrypted.Signature) != signatureLength {
x.Errorf("failed with seed %d: signature len %d.", seed, len(decrypted.Signature)) t.Fatalf("failed with seed %d: signature len %d.", seed, len(decrypted.Signature))
return
} }
if !isPubKeyEqual(decrypted.Src, &params.Src.PublicKey) { if !isPubKeyEqual(decrypted.Src, &params.Src.PublicKey) {
x.Errorf("failed with seed %d: signature mismatch.", seed) t.Fatalf("failed with seed %d: signature mismatch.", seed)
return
} }
if decrypted.isAsymmetricEncryption() == symmetric { if decrypted.isAsymmetricEncryption() == symmetric {
x.Errorf("failed with seed %d: asymmetric %v vs. %v.", seed, decrypted.isAsymmetricEncryption(), symmetric) t.Fatalf("failed with seed %d: asymmetric %v vs. %v.", seed, decrypted.isAsymmetricEncryption(), symmetric)
return
} }
if decrypted.isSymmetricEncryption() != symmetric { if decrypted.isSymmetricEncryption() != symmetric {
x.Errorf("failed with seed %d: symmetric %v vs. %v.", seed, decrypted.isSymmetricEncryption(), symmetric) t.Fatalf("failed with seed %d: symmetric %v vs. %v.", seed, decrypted.isSymmetricEncryption(), symmetric)
return
} }
if !symmetric { if !symmetric {
if decrypted.Dst == nil { if decrypted.Dst == nil {
x.Errorf("failed with seed %d: dst is nil.", seed) t.Fatalf("failed with seed %d: dst is nil.", seed)
return
} }
if !isPubKeyEqual(decrypted.Dst, &key.PublicKey) { if !isPubKeyEqual(decrypted.Dst, &key.PublicKey) {
x.Errorf("failed with seed %d: Dst.", seed) t.Fatalf("failed with seed %d: Dst.", seed)
return
} }
} }
} }

View File

@ -165,6 +165,9 @@ func (p *Peer) broadcast() error {
p.mark(envelope) p.mark(envelope)
} }
} }
if len(transmit) == 0 {
return nil
}
// Transmit the unknown batch (potentially empty) // Transmit the unknown batch (potentially empty)
if err := p2p.Send(p.ws, messagesCode, transmit); err != nil { if err := p2p.Send(p.ws, messagesCode, transmit); err != nil {
return err return err

View File

@ -79,7 +79,7 @@ type TestNode struct {
shh *Whisper shh *Whisper
id *ecdsa.PrivateKey id *ecdsa.PrivateKey
server *p2p.Server server *p2p.Server
filerId int filerId uint32
} }
var result TestData var result TestData
@ -94,19 +94,19 @@ var expectedMessage []byte = []byte("per rectum ad astra")
// 3. each node sends a number of random (undecryptable) messages, // 3. each node sends a number of random (undecryptable) messages,
// 4. first node sends one expected (decryptable) message, // 4. first node sends one expected (decryptable) message,
// 5. checks if each node have received and decrypted exactly one message. // 5. checks if each node have received and decrypted exactly one message.
func TestSimulation(x *testing.T) { func TestSimulation(t *testing.T) {
initialize(x) initialize(t)
for i := 0; i < NumNodes; i++ { for i := 0; i < NumNodes; i++ {
sendMsg(x, false, i) sendMsg(t, false, i)
} }
sendMsg(x, true, 0) sendMsg(t, true, 0)
checkPropagation(x) checkPropagation(t)
stopServers() stopServers()
} }
func initialize(x *testing.T) { func initialize(t *testing.T) {
//glog.SetV(6) //glog.SetV(6)
//glog.SetToStderr(true) //glog.SetToStderr(true)
@ -118,14 +118,13 @@ func initialize(x *testing.T) {
var node TestNode var node TestNode
node.shh = NewWhisper(nil) node.shh = NewWhisper(nil)
node.shh.test = true node.shh.test = true
tt := make([]TopicType, 0) topics := make([]TopicType, 0)
tt = append(tt, sharedTopic) topics = append(topics, sharedTopic)
f := Filter{KeySym: sharedKey, Topics: tt} f := Filter{KeySym: sharedKey, Topics: topics}
node.filerId = node.shh.Watch(&f) node.filerId = node.shh.Watch(&f)
node.id, err = crypto.HexToECDSA(keys[i]) node.id, err = crypto.HexToECDSA(keys[i])
if err != nil { if err != nil {
x.Errorf("failed convert the key: %s.", keys[i]) t.Fatalf("failed convert the key: %s.", keys[i])
return
} }
port := port0 + i port := port0 + i
addr := fmt.Sprintf(":%d", port) // e.g. ":30303" addr := fmt.Sprintf(":%d", port) // e.g. ":30303"
@ -155,8 +154,7 @@ func initialize(x *testing.T) {
err = node.server.Start() err = node.server.Start()
if err != nil { if err != nil {
x.Errorf("failed to start server %d.", i) t.Fatalf("failed to start server %d.", i)
return
} }
nodes[i] = &node nodes[i] = &node
@ -173,8 +171,8 @@ func stopServers() {
} }
} }
func checkPropagation(x *testing.T) { func checkPropagation(t *testing.T) {
if x.Failed() { if t.Failed() {
return return
} }
@ -187,26 +185,24 @@ func checkPropagation(x *testing.T) {
for i := 0; i < NumNodes; i++ { for i := 0; i < NumNodes; i++ {
f := nodes[i].shh.GetFilter(nodes[i].filerId) f := nodes[i].shh.GetFilter(nodes[i].filerId)
if f == nil { if f == nil {
x.Errorf("failed to get filterId %d from node %d.", nodes[i].filerId, i) t.Fatalf("failed to get filterId %d from node %d.", nodes[i].filerId, i)
return
} }
mail := f.Retrieve() mail := f.Retrieve()
if !validateMail(x, i, mail) { if !validateMail(t, i, mail) {
return return
} }
if isTestComplete() { if isTestComplete() {
return return
} }
} }
} }
x.Errorf("Test was not complete: timeout %d seconds.", iterations*cycle/1000) t.Fatalf("Test was not complete: timeout %d seconds.", iterations*cycle/1000)
} }
func validateMail(x *testing.T, index int, mail []*ReceivedMessage) bool { func validateMail(t *testing.T, index int, mail []*ReceivedMessage) bool {
var cnt int var cnt int
for _, m := range mail { for _, m := range mail {
if bytes.Compare(m.Payload, expectedMessage) == 0 { if bytes.Compare(m.Payload, expectedMessage) == 0 {
@ -219,7 +215,7 @@ func validateMail(x *testing.T, index int, mail []*ReceivedMessage) bool {
return true return true
} }
if cnt > 1 { if cnt > 1 {
x.Errorf("node %d received %d.", index, cnt) t.Fatalf("node %d received %d.", index, cnt)
return false return false
} }
@ -228,8 +224,7 @@ func validateMail(x *testing.T, index int, mail []*ReceivedMessage) bool {
defer result.mutex.Unlock() defer result.mutex.Unlock()
result.counter[index] += cnt result.counter[index] += cnt
if result.counter[index] > 1 { if result.counter[index] > 1 {
x.Errorf("node %d accumulated %d.", index, result.counter[index]) t.Fatalf("node %d accumulated %d.", index, result.counter[index])
return false
} }
} }
return true return true
@ -255,8 +250,8 @@ func isTestComplete() bool {
return true return true
} }
func sendMsg(x *testing.T, expected bool, id int) { func sendMsg(t *testing.T, expected bool, id int) {
if x.Failed() { if t.Failed() {
return return
} }
@ -270,38 +265,33 @@ func sendMsg(x *testing.T, expected bool, id int) {
msg := NewSentMessage(&opt) msg := NewSentMessage(&opt)
envelope, err := msg.Wrap(&opt) envelope, err := msg.Wrap(&opt)
if err != nil { if err != nil {
x.Errorf("failed to seal message.") t.Fatalf("failed to seal message.")
return
} }
err = nodes[id].shh.Send(envelope) err = nodes[id].shh.Send(envelope)
if err != nil { if err != nil {
x.Errorf("failed to send message.") t.Fatalf("failed to send message.")
return
} }
} }
func TestPeerBasic(x *testing.T) { func TestPeerBasic(t *testing.T) {
InitSingleTest() InitSingleTest()
params, err := generateMessageParams() params, err := generateMessageParams()
if err != nil { if err != nil {
x.Errorf("failed 1 with seed %d.", seed) t.Fatalf("failed generateMessageParams with seed %d.", seed)
return
} }
params.PoW = 0.001 params.PoW = 0.001
msg := NewSentMessage(params) msg := NewSentMessage(params)
env, err := msg.Wrap(params) env, err := msg.Wrap(params)
if err != nil { if err != nil {
x.Errorf("failed 2 with seed %d.", seed) t.Fatalf("failed Wrap with seed %d.", seed)
return
} }
p := newPeer(nil, nil, nil) p := newPeer(nil, nil, nil)
p.mark(env) p.mark(env)
if !p.marked(env) { if !p.marked(env) {
x.Errorf("failed 3 with seed %d.", seed) t.Fatalf("failed mark with seed %d.", seed)
return
} }
} }

View File

@ -28,11 +28,11 @@ var topicStringTests = []struct {
{topic: TopicType{0xf2, 0x6e, 0x77, 0x79}, str: "0xf26e7779"}, {topic: TopicType{0xf2, 0x6e, 0x77, 0x79}, str: "0xf26e7779"},
} }
func TestTopicString(x *testing.T) { func TestTopicString(t *testing.T) {
for i, tst := range topicStringTests { for i, tst := range topicStringTests {
s := tst.topic.String() s := tst.topic.String()
if s != tst.str { if s != tst.str {
x.Errorf("failed test %d: have %s, want %s.", i, s, tst.str) t.Fatalf("failed test %d: have %s, want %s.", i, s, tst.str)
} }
} }
} }
@ -53,11 +53,11 @@ var bytesToTopicTests = []struct {
{topic: TopicType{0x00, 0x00, 0x00, 0x00}, data: nil}, {topic: TopicType{0x00, 0x00, 0x00, 0x00}, data: nil},
} }
func TestBytesToTopic(x *testing.T) { func TestBytesToTopic(t *testing.T) {
for i, tst := range bytesToTopicTests { for i, tst := range bytesToTopicTests {
t := BytesToTopic(tst.data) top := BytesToTopic(tst.data)
if t != tst.topic { if top != tst.topic {
x.Errorf("failed test %d: have %v, want %v.", i, t, tst.topic) t.Fatalf("failed test %d: have %v, want %v.", i, t, tst.topic)
} }
} }
} }
@ -99,38 +99,38 @@ var unmarshalTestsUgly = []struct {
{topic: TopicType{0x01, 0x00, 0x00, 0x00}, data: []byte("00000001")}, {topic: TopicType{0x01, 0x00, 0x00, 0x00}, data: []byte("00000001")},
} }
func TestUnmarshalTestsGood(x *testing.T) { func TestUnmarshalTestsGood(t *testing.T) {
for i, tst := range unmarshalTestsGood { for i, tst := range unmarshalTestsGood {
var t TopicType var top TopicType
err := t.UnmarshalJSON(tst.data) err := top.UnmarshalJSON(tst.data)
if err != nil { if err != nil {
x.Errorf("failed test %d. input: %v.", i, tst.data) t.Fatalf("failed test %d. input: %v.", i, tst.data)
} else if t != tst.topic { } else if top != tst.topic {
x.Errorf("failed test %d: have %v, want %v.", i, t, tst.topic) t.Fatalf("failed test %d: have %v, want %v.", i, t, tst.topic)
} }
} }
} }
func TestUnmarshalTestsBad(x *testing.T) { func TestUnmarshalTestsBad(t *testing.T) {
// in this test UnmarshalJSON() is supposed to fail // in this test UnmarshalJSON() is supposed to fail
for i, tst := range unmarshalTestsBad { for i, tst := range unmarshalTestsBad {
var t TopicType var top TopicType
err := t.UnmarshalJSON(tst.data) err := top.UnmarshalJSON(tst.data)
if err == nil { if err == nil {
x.Errorf("failed test %d. input: %v.", i, tst.data) t.Fatalf("failed test %d. input: %v.", i, tst.data)
} }
} }
} }
func TestUnmarshalTestsUgly(x *testing.T) { func TestUnmarshalTestsUgly(t *testing.T) {
// in this test UnmarshalJSON() is NOT supposed to fail, but result should be wrong // in this test UnmarshalJSON() is NOT supposed to fail, but result should be wrong
for i, tst := range unmarshalTestsUgly { for i, tst := range unmarshalTestsUgly {
var t TopicType var top TopicType
err := t.UnmarshalJSON(tst.data) err := top.UnmarshalJSON(tst.data)
if err != nil { if err != nil {
x.Errorf("failed test %d. input: %v.", i, tst.data) t.Fatalf("failed test %d. input: %v.", i, tst.data)
} else if t == tst.topic { } else if top == tst.topic {
x.Errorf("failed test %d: have %v, want %v.", i, t, tst.topic) t.Fatalf("failed test %d: have %v, want %v.", i, top, tst.topic)
} }
} }
} }

View File

@ -177,12 +177,13 @@ func (w *Whisper) GetIdentity(pubKey string) *ecdsa.PrivateKey {
} }
func (w *Whisper) GenerateSymKey(name string) error { func (w *Whisper) GenerateSymKey(name string) error {
buf := make([]byte, aesKeyLength*2) const size = aesKeyLength * 2
_, err := crand.Read(buf) // todo: check how safe is this function buf := make([]byte, size)
_, err := crand.Read(buf)
if err != nil { if err != nil {
return err return err
} else if !validateSymmetricKey(buf) { } else if !validateSymmetricKey(buf) {
return fmt.Errorf("crypto/rand failed to generate random data") return fmt.Errorf("error in GenerateSymKey: crypto/rand failed to generate random data")
} }
key := buf[:aesKeyLength] key := buf[:aesKeyLength]
@ -245,16 +246,16 @@ func (w *Whisper) GetSymKey(name string) []byte {
// Watch installs a new message handler to run in case a matching packet arrives // Watch installs a new message handler to run in case a matching packet arrives
// from the whisper network. // from the whisper network.
func (w *Whisper) Watch(f *Filter) int { func (w *Whisper) Watch(f *Filter) uint32 {
return w.filters.Install(f) return w.filters.Install(f)
} }
func (w *Whisper) GetFilter(id int) *Filter { func (w *Whisper) GetFilter(id uint32) *Filter {
return w.filters.Get(id) return w.filters.Get(id)
} }
// Unwatch removes an installed message handler. // Unwatch removes an installed message handler.
func (w *Whisper) Unwatch(id int) { func (w *Whisper) Unwatch(id uint32) {
w.filters.Uninstall(id) w.filters.Uninstall(id)
} }
@ -404,7 +405,7 @@ func (wh *Whisper) add(envelope *Envelope) error {
return fmt.Errorf("oversized Version") return fmt.Errorf("oversized Version")
} }
if len(envelope.AESNonce) > 12 { if len(envelope.AESNonce) > AESNonceMaxLength {
// the standard AES GSM nonce size is 12, // the standard AES GSM nonce size is 12,
// but const gcmStandardNonceSize cannot be accessed directly // but const gcmStandardNonceSize cannot be accessed directly
return fmt.Errorf("oversized AESNonce") return fmt.Errorf("oversized AESNonce")
@ -507,7 +508,7 @@ func (w *Whisper) Envelopes() []*Envelope {
} }
// Messages retrieves all the decrypted messages matching a filter id. // Messages retrieves all the decrypted messages matching a filter id.
func (w *Whisper) Messages(id int) []*ReceivedMessage { func (w *Whisper) Messages(id uint32) []*ReceivedMessage {
result := make([]*ReceivedMessage, 0) result := make([]*ReceivedMessage, 0)
w.poolMu.RLock() w.poolMu.RLock()
defer w.poolMu.RUnlock() defer w.poolMu.RUnlock()

View File

@ -24,123 +24,101 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
) )
func TestWhisperBasic(x *testing.T) { func TestWhisperBasic(t *testing.T) {
w := NewWhisper(nil) w := NewWhisper(nil)
p := w.Protocols() p := w.Protocols()
shh := p[0] shh := p[0]
if shh.Name != ProtocolName { if shh.Name != ProtocolName {
x.Errorf("failed Protocol Name: %v.", shh.Name) t.Fatalf("failed Protocol Name: %v.", shh.Name)
return
} }
if uint64(shh.Version) != ProtocolVersion { if uint64(shh.Version) != ProtocolVersion {
x.Errorf("failed Protocol Version: %v.", shh.Version) t.Fatalf("failed Protocol Version: %v.", shh.Version)
return
} }
if shh.Length != NumberOfMessageCodes { if shh.Length != NumberOfMessageCodes {
x.Errorf("failed Protocol Length: %v.", shh.Length) t.Fatalf("failed Protocol Length: %v.", shh.Length)
return
} }
if shh.Run == nil { if shh.Run == nil {
x.Errorf("failed shh.Run.") t.Fatalf("failed shh.Run.")
return
} }
if uint64(w.Version()) != ProtocolVersion { if uint64(w.Version()) != ProtocolVersion {
x.Errorf("failed whisper Version: %v.", shh.Version) t.Fatalf("failed whisper Version: %v.", shh.Version)
return
} }
if w.GetFilter(0) != nil { if w.GetFilter(0) != nil {
x.Errorf("failed GetFilter.") t.Fatalf("failed GetFilter.")
return
} }
peerID := make([]byte, 64) peerID := make([]byte, 64)
randomize(peerID) randomize(peerID)
peer, err := w.getPeer(peerID) peer, err := w.getPeer(peerID)
if peer != nil { if peer != nil {
x.Errorf("failed GetPeer.") t.Fatalf("failed GetPeer.")
return
} }
err = w.MarkPeerTrusted(peerID) err = w.MarkPeerTrusted(peerID)
if err == nil { if err == nil {
x.Errorf("failed MarkPeerTrusted.") t.Fatalf("failed MarkPeerTrusted.")
return
} }
err = w.RequestHistoricMessages(peerID, peerID) err = w.RequestHistoricMessages(peerID, peerID)
if err == nil { if err == nil {
x.Errorf("failed RequestHistoricMessages.") t.Fatalf("failed RequestHistoricMessages.")
return
} }
err = w.SendP2PMessage(peerID, nil) err = w.SendP2PMessage(peerID, nil)
if err == nil { if err == nil {
x.Errorf("failed SendP2PMessage.") t.Fatalf("failed SendP2PMessage.")
return
} }
exist := w.HasSymKey("non-existing") exist := w.HasSymKey("non-existing")
if exist { if exist {
x.Errorf("failed HasSymKey.") t.Fatalf("failed HasSymKey.")
return
} }
key := w.GetSymKey("non-existing") key := w.GetSymKey("non-existing")
if key != nil { if key != nil {
x.Errorf("failed GetSymKey.") t.Fatalf("failed GetSymKey.")
return
} }
mail := w.Envelopes() mail := w.Envelopes()
if len(mail) != 0 { if len(mail) != 0 {
x.Errorf("failed w.Envelopes().") t.Fatalf("failed w.Envelopes().")
return
} }
m := w.Messages(0) m := w.Messages(0)
if len(m) != 0 { if len(m) != 0 {
x.Errorf("failed w.Messages.") t.Fatalf("failed w.Messages.")
return
} }
var derived []byte var derived []byte
ver := uint64(0xDEADBEEF) ver := uint64(0xDEADBEEF)
derived, err = deriveKeyMaterial(peerID, ver) derived, err = deriveKeyMaterial(peerID, ver)
if err != unknownVersionError(ver) { if err != unknownVersionError(ver) {
x.Errorf("failed deriveKeyMaterial 1 with param = %v: %s.", peerID, err) t.Fatalf("failed deriveKeyMaterial with param = %v: %s.", peerID, err)
return
} }
derived, err = deriveKeyMaterial(peerID, 0) derived, err = deriveKeyMaterial(peerID, 0)
if err != nil { if err != nil {
x.Errorf("failed deriveKeyMaterial 2 with param = %v: %s.", peerID, err) t.Fatalf("failed second deriveKeyMaterial with param = %v: %s.", peerID, err)
return
} }
if !validateSymmetricKey(derived) { if !validateSymmetricKey(derived) {
x.Errorf("failed validateSymmetricKey with param = %v.", derived) t.Fatalf("failed validateSymmetricKey with param = %v.", derived)
return
} }
if containsOnlyZeros(derived) { if containsOnlyZeros(derived) {
x.Errorf("failed containsOnlyZeros with param = %v.", derived) t.Fatalf("failed containsOnlyZeros with param = %v.", derived)
return
} }
buf := []byte{0xFF, 0xE5, 0x80, 0x2, 0} buf := []byte{0xFF, 0xE5, 0x80, 0x2, 0}
le := bytesToIntLittleEndian(buf) le := bytesToIntLittleEndian(buf)
be := BytesToIntBigEndian(buf) be := BytesToIntBigEndian(buf)
if le != uint64(0x280e5ff) { if le != uint64(0x280e5ff) {
x.Errorf("failed bytesToIntLittleEndian: %d.", le) t.Fatalf("failed bytesToIntLittleEndian: %d.", le)
return
} }
if be != uint64(0xffe5800200) { if be != uint64(0xffe5800200) {
x.Errorf("failed BytesToIntBigEndian: %d.", be) t.Fatalf("failed BytesToIntBigEndian: %d.", be)
return
} }
pk := w.NewIdentity() pk := w.NewIdentity()
if !validatePrivateKey(pk) { if !validatePrivateKey(pk) {
x.Errorf("failed validatePrivateKey: %v.", pk) t.Fatalf("failed validatePrivateKey: %v.", pk)
return
} }
if !ValidatePublicKey(&pk.PublicKey) { if !ValidatePublicKey(&pk.PublicKey) {
x.Errorf("failed ValidatePublicKey: %v.", pk) t.Fatalf("failed ValidatePublicKey: %v.", pk)
return
} }
} }
func TestWhisperIdentityManagement(x *testing.T) { func TestWhisperIdentityManagement(t *testing.T) {
w := NewWhisper(nil) w := NewWhisper(nil)
id1 := w.NewIdentity() id1 := w.NewIdentity()
id2 := w.NewIdentity() id2 := w.NewIdentity()
@ -149,20 +127,16 @@ func TestWhisperIdentityManagement(x *testing.T) {
pk1 := w.GetIdentity(pub1) pk1 := w.GetIdentity(pub1)
pk2 := w.GetIdentity(pub2) pk2 := w.GetIdentity(pub2)
if !w.HasIdentity(pub1) { if !w.HasIdentity(pub1) {
x.Errorf("failed HasIdentity 1.") t.Fatalf("failed HasIdentity(pub1).")
return
} }
if !w.HasIdentity(pub2) { if !w.HasIdentity(pub2) {
x.Errorf("failed HasIdentity 2.") t.Fatalf("failed HasIdentity(pub2).")
return
} }
if pk1 != id1 { if pk1 != id1 {
x.Errorf("failed GetIdentity 3.") t.Fatalf("failed GetIdentity(pub1).")
return
} }
if pk2 != id2 { if pk2 != id2 {
x.Errorf("failed GetIdentity 4.") t.Fatalf("failed GetIdentity(pub2).")
return
} }
// Delete one identity // Delete one identity
@ -170,20 +144,16 @@ func TestWhisperIdentityManagement(x *testing.T) {
pk1 = w.GetIdentity(pub1) pk1 = w.GetIdentity(pub1)
pk2 = w.GetIdentity(pub2) pk2 = w.GetIdentity(pub2)
if w.HasIdentity(pub1) { if w.HasIdentity(pub1) {
x.Errorf("failed HasIdentity 11.") t.Fatalf("failed DeleteIdentity(pub1): still exist.")
return
} }
if !w.HasIdentity(pub2) { if !w.HasIdentity(pub2) {
x.Errorf("failed HasIdentity 12.") t.Fatalf("failed DeleteIdentity(pub1): pub2 does not exist.")
return
} }
if pk1 != nil { if pk1 != nil {
x.Errorf("failed GetIdentity 13.") t.Fatalf("failed DeleteIdentity(pub1): first key still exist.")
return
} }
if pk2 != id2 { if pk2 != id2 {
x.Errorf("failed GetIdentity 14.") t.Fatalf("failed DeleteIdentity(pub1): second key does not exist.")
return
} }
// Delete again non-existing identity // Delete again non-existing identity
@ -191,20 +161,16 @@ func TestWhisperIdentityManagement(x *testing.T) {
pk1 = w.GetIdentity(pub1) pk1 = w.GetIdentity(pub1)
pk2 = w.GetIdentity(pub2) pk2 = w.GetIdentity(pub2)
if w.HasIdentity(pub1) { if w.HasIdentity(pub1) {
x.Errorf("failed HasIdentity 21.") t.Fatalf("failed delete non-existing identity: exist.")
return
} }
if !w.HasIdentity(pub2) { if !w.HasIdentity(pub2) {
x.Errorf("failed HasIdentity 22.") t.Fatalf("failed delete non-existing identity: pub2 does not exist.")
return
} }
if pk1 != nil { if pk1 != nil {
x.Errorf("failed GetIdentity 23.") t.Fatalf("failed delete non-existing identity: first key exist.")
return
} }
if pk2 != id2 { if pk2 != id2 {
x.Errorf("failed GetIdentity 24.") t.Fatalf("failed delete non-existing identity: second key does not exist.")
return
} }
// Delete second identity // Delete second identity
@ -212,24 +178,20 @@ func TestWhisperIdentityManagement(x *testing.T) {
pk1 = w.GetIdentity(pub1) pk1 = w.GetIdentity(pub1)
pk2 = w.GetIdentity(pub2) pk2 = w.GetIdentity(pub2)
if w.HasIdentity(pub1) { if w.HasIdentity(pub1) {
x.Errorf("failed HasIdentity 31.") t.Fatalf("failed delete second identity: first identity exist.")
return
} }
if w.HasIdentity(pub2) { if w.HasIdentity(pub2) {
x.Errorf("failed HasIdentity 32.") t.Fatalf("failed delete second identity: still exist.")
return
} }
if pk1 != nil { if pk1 != nil {
x.Errorf("failed GetIdentity 33.") t.Fatalf("failed delete second identity: first key exist.")
return
} }
if pk2 != nil { if pk2 != nil {
x.Errorf("failed GetIdentity 34.") t.Fatalf("failed delete second identity: second key exist.")
return
} }
} }
func TestWhisperSymKeyManagement(x *testing.T) { func TestWhisperSymKeyManagement(t *testing.T) {
InitSingleTest() InitSingleTest()
var k1, k2 []byte var k1, k2 []byte
@ -239,27 +201,22 @@ func TestWhisperSymKeyManagement(x *testing.T) {
err := w.GenerateSymKey(id1) err := w.GenerateSymKey(id1)
if err != nil { if err != nil {
x.Errorf("failed test case 1 with seed %d: %s.", seed, err) t.Fatalf("failed GenerateSymKey with seed %d: %s.", seed, err)
return
} }
k1 = w.GetSymKey(id1) k1 = w.GetSymKey(id1)
k2 = w.GetSymKey(id2) k2 = w.GetSymKey(id2)
if !w.HasSymKey(id1) { if !w.HasSymKey(id1) {
x.Errorf("failed HasIdentity 2.") t.Fatalf("failed HasSymKey(id1).")
return
} }
if w.HasSymKey(id2) { if w.HasSymKey(id2) {
x.Errorf("failed HasIdentity 3.") t.Fatalf("failed HasSymKey(id2).")
return
} }
if k1 == nil { if k1 == nil {
x.Errorf("failed GetIdentity 4.") t.Fatalf("first key does not exist.")
return
} }
if k2 != nil { if k2 != nil {
x.Errorf("failed GetIdentity 5.") t.Fatalf("second key still exist.")
return
} }
// add existing id, nothing should change // add existing id, nothing should change
@ -267,91 +224,72 @@ func TestWhisperSymKeyManagement(x *testing.T) {
randomize(randomKey) randomize(randomKey)
err = w.AddSymKey(id1, randomKey) err = w.AddSymKey(id1, randomKey)
if err == nil { if err == nil {
x.Errorf("failed test case 10 with seed %d.", seed) t.Fatalf("failed AddSymKey with seed %d.", seed)
return
} }
k1 = w.GetSymKey(id1) k1 = w.GetSymKey(id1)
k2 = w.GetSymKey(id2) k2 = w.GetSymKey(id2)
if !w.HasSymKey(id1) { if !w.HasSymKey(id1) {
x.Errorf("failed HasIdentity 12.") t.Fatalf("failed w.HasSymKey(id1).")
return
} }
if w.HasSymKey(id2) { if w.HasSymKey(id2) {
x.Errorf("failed HasIdentity 13.") t.Fatalf("failed w.HasSymKey(id2).")
return
} }
if k1 == nil { if k1 == nil {
x.Errorf("failed GetIdentity 14.") t.Fatalf("first key does not exist.")
return
} }
if bytes.Compare(k1, randomKey) == 0 { if bytes.Compare(k1, randomKey) == 0 {
x.Errorf("failed GetIdentity 15: k1 == randomKey.") t.Fatalf("k1 == randomKey.")
return
} }
if k2 != nil { if k2 != nil {
x.Errorf("failed GetIdentity 16.") t.Fatalf("second key already exist.")
return
} }
err = w.AddSymKey(id2, randomKey) // add non-existing (yet) err = w.AddSymKey(id2, randomKey) // add non-existing (yet)
if err != nil { if err != nil {
x.Errorf("failed test case 21 with seed %d: %s.", seed, err) t.Fatalf("failed AddSymKey(id2) with seed %d: %s.", seed, err)
return
} }
k1 = w.GetSymKey(id1) k1 = w.GetSymKey(id1)
k2 = w.GetSymKey(id2) k2 = w.GetSymKey(id2)
if !w.HasSymKey(id1) { if !w.HasSymKey(id1) {
x.Errorf("failed HasIdentity 22.") t.Fatalf("HasSymKey(id1) failed.")
return
} }
if !w.HasSymKey(id2) { if !w.HasSymKey(id2) {
x.Errorf("failed HasIdentity 23.") t.Fatalf("HasSymKey(id2) failed.")
return
} }
if k1 == nil { if k1 == nil {
x.Errorf("failed GetIdentity 24.") t.Fatalf("k1 does not exist.")
return
} }
if k2 == nil { if k2 == nil {
x.Errorf("failed GetIdentity 25.") t.Fatalf("k2 does not exist.")
return
} }
if bytes.Compare(k1, k2) == 0 { if bytes.Compare(k1, k2) == 0 {
x.Errorf("failed GetIdentity 26.") t.Fatalf("k1 == k2.")
return
} }
if bytes.Compare(k1, randomKey) == 0 { if bytes.Compare(k1, randomKey) == 0 {
x.Errorf("failed GetIdentity 27.") t.Fatalf("k1 == randomKey.")
return
} }
if len(k1) != aesKeyLength { if len(k1) != aesKeyLength {
x.Errorf("failed GetIdentity 28.") t.Fatalf("wrong length of k1.")
return
} }
if len(k2) != aesKeyLength { if len(k2) != aesKeyLength {
x.Errorf("failed GetIdentity 29.") t.Fatalf("wrong length of k2.")
return
} }
w.DeleteSymKey(id1) w.DeleteSymKey(id1)
k1 = w.GetSymKey(id1) k1 = w.GetSymKey(id1)
k2 = w.GetSymKey(id2) k2 = w.GetSymKey(id2)
if w.HasSymKey(id1) { if w.HasSymKey(id1) {
x.Errorf("failed HasIdentity 31.") t.Fatalf("failed to delete first key: still exist.")
return
} }
if !w.HasSymKey(id2) { if !w.HasSymKey(id2) {
x.Errorf("failed HasIdentity 32.") t.Fatalf("failed to delete first key: second key does not exist.")
return
} }
if k1 != nil { if k1 != nil {
x.Errorf("failed GetIdentity 33.") t.Fatalf("failed to delete first key.")
return
} }
if k2 == nil { if k2 == nil {
x.Errorf("failed GetIdentity 34.") t.Fatalf("failed to delete first key: second key is nil.")
return
} }
w.DeleteSymKey(id1) w.DeleteSymKey(id1)
@ -359,19 +297,15 @@ func TestWhisperSymKeyManagement(x *testing.T) {
k1 = w.GetSymKey(id1) k1 = w.GetSymKey(id1)
k2 = w.GetSymKey(id2) k2 = w.GetSymKey(id2)
if w.HasSymKey(id1) { if w.HasSymKey(id1) {
x.Errorf("failed HasIdentity 41.") t.Fatalf("failed to delete second key: first key exist.")
return
} }
if w.HasSymKey(id2) { if w.HasSymKey(id2) {
x.Errorf("failed HasIdentity 42.") t.Fatalf("failed to delete second key: still exist.")
return
} }
if k1 != nil { if k1 != nil {
x.Errorf("failed GetIdentity 43.") t.Fatalf("failed to delete second key: first key is not nil.")
return
} }
if k2 != nil { if k2 != nil {
x.Errorf("failed GetIdentity 44.") t.Fatalf("failed to delete second key: second key is not nil.")
return
} }
} }