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
release/1.5
gluk256 8 years ago committed by Felix Lange
parent 671fd94e25
commit 2dcf75a722
  1. 101
      whisper/shhapi/api.go
  2. 504
      whisper/shhapi/api_test.go
  3. 57
      whisper/whisperv5/benchmarks_test.go
  4. 11
      whisper/whisperv5/doc.go
  5. 4
      whisper/whisperv5/envelope.go
  6. 56
      whisper/whisperv5/filter.go
  7. 300
      whisper/whisperv5/filter_test.go
  8. 5
      whisper/whisperv5/message.go
  9. 106
      whisper/whisperv5/message_test.go
  10. 3
      whisper/whisperv5/peer.go
  11. 66
      whisper/whisperv5/peer_test.go
  12. 44
      whisper/whisperv5/topic_test.go
  13. 17
      whisper/whisperv5/whisper.go
  14. 204
      whisper/whisperv5/whisper_test.go

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

@ -17,88 +17,77 @@
package shhapi
import (
"bytes"
"testing"
"time"
"github.com/ethereum/go-ethereum/rpc"
"encoding/json"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/whisper/whisperv5"
)
func TestBasic(x *testing.T) {
func TestBasic(t *testing.T) {
var id string = "test"
api := NewPublicWhisperAPI()
if api == nil {
x.Errorf("failed to create API.")
return
t.Fatalf("failed to create API.")
}
ver, err := api.Version()
if err != nil {
x.Errorf("failed generateFilter: %s.", err)
return
t.Fatalf("failed generateFilter: %s.", err)
}
if ver.Uint64() != whisperv5.ProtocolVersion {
x.Errorf("wrong version: %d.", ver.Uint64())
return
t.Fatalf("wrong version: %d.", ver.Uint64())
}
var hexnum rpc.HexNumber
mail := api.GetFilterChanges(hexnum)
mail := api.GetFilterChanges(1)
if len(mail) != 0 {
x.Errorf("failed GetFilterChanges")
return
t.Fatalf("failed GetFilterChanges: premature result")
}
exist, err := api.HasIdentity(id)
if err != nil {
x.Errorf("failed 1 HasIdentity: %s.", err)
return
t.Fatalf("failed initial HasIdentity: %s.", err)
}
if exist {
x.Errorf("failed 2 HasIdentity: false positive.")
return
t.Fatalf("failed initial HasIdentity: false positive.")
}
err = api.DeleteIdentity(id)
if err != nil {
x.Errorf("failed 3 DeleteIdentity: %s.", err)
return
t.Fatalf("failed DeleteIdentity: %s.", err)
}
pub, err := api.NewIdentity()
if err != nil {
x.Errorf("failed 4 NewIdentity: %s.", err)
return
t.Fatalf("failed NewIdentity: %s.", err)
}
if len(pub) == 0 {
x.Errorf("NewIdentity 5: empty")
return
t.Fatalf("failed NewIdentity: empty")
}
exist, err = api.HasIdentity(pub)
if err != nil {
x.Errorf("failed 6 HasIdentity: %s.", err)
return
t.Fatalf("failed HasIdentity: %s.", err)
}
if !exist {
x.Errorf("failed 7 HasIdentity: false negative.")
return
t.Fatalf("failed HasIdentity: false negative.")
}
err = api.DeleteIdentity(pub)
if err != nil {
x.Errorf("failed 8 DeleteIdentity: %s.", err)
return
t.Fatalf("failed to delete second identity: %s.", err)
}
exist, err = api.HasIdentity(pub)
if err != nil {
x.Errorf("failed 9 HasIdentity: %s.", err)
return
t.Fatalf("failed HasIdentity(): %s.", err)
}
if exist {
x.Errorf("failed 10 HasIdentity: false positive.")
return
t.Fatalf("failed HasIdentity(): false positive.")
}
id = "arbitrary text"
@ -106,65 +95,468 @@ func TestBasic(x *testing.T) {
exist, err = api.HasSymKey(id)
if err != nil {
x.Errorf("failed 11 HasSymKey: %s.", err)
return
t.Fatalf("failed HasSymKey: %s.", err)
}
if exist {
x.Errorf("failed 12 HasSymKey: false positive.")
return
t.Fatalf("failed HasSymKey: false positive.")
}
err = api.GenerateSymKey(id)
if err != nil {
x.Errorf("failed 13 GenerateSymKey: %s.", err)
return
t.Fatalf("failed GenerateSymKey: %s.", err)
}
exist, err = api.HasSymKey(id)
if err != nil {
x.Errorf("failed 14 HasSymKey: %s.", err)
return
t.Fatalf("failed HasSymKey(): %s.", err)
}
if !exist {
x.Errorf("failed 15 HasSymKey: false negative.")
return
t.Fatalf("failed HasSymKey(): false negative.")
}
err = api.AddSymKey(id, []byte("some stuff here"))
if err == nil {
x.Errorf("failed 16 AddSymKey: %s.", err)
return
t.Fatalf("failed AddSymKey: %s.", err)
}
err = api.AddSymKey(id2, []byte("some stuff here"))
if err != nil {
x.Errorf("failed 17 AddSymKey: %s.", err)
return
t.Fatalf("failed AddSymKey: %s.", err)
}
exist, err = api.HasSymKey(id2)
if err != nil {
x.Errorf("failed 18 HasSymKey: %s.", err)
return
t.Fatalf("failed HasSymKey(id2): %s.", err)
}
if !exist {
x.Errorf("failed 19 HasSymKey: false negative.")
return
t.Fatalf("failed HasSymKey(id2): false negative.")
}
err = api.DeleteSymKey(id)
if err != nil {
x.Errorf("failed 20 DeleteSymKey: %s.", err)
return
t.Fatalf("failed DeleteSymKey(id): %s.", err)
}
exist, err = api.HasSymKey(id)
if err != nil {
x.Errorf("failed 21 HasSymKey: %s.", err)
return
t.Fatalf("failed HasSymKey(id): %s.", err)
}
if exist {
x.Errorf("failed 22 HasSymKey: false positive.")
return
t.Fatalf("failed HasSymKey(id): false positive.")
}
}
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)
}
}

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

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

@ -73,7 +73,7 @@ func NewEnvelope(ttl uint32, topic TopicType, salt []byte, aesNonce []byte, msg
}
func (e *Envelope) IsSymmetric() bool {
return e.AESNonce != nil
return len(e.AESNonce) > 0
}
func (e *Envelope) isAsymmetric() bool {
@ -131,7 +131,7 @@ func (e *Envelope) calculatePoW(diff uint32) {
h = crypto.Keccak256(buf)
firstBit := common.FirstBitSet(common.BigD(h))
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)
e.pow = x
}

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

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

@ -130,7 +130,7 @@ func (msg *SentMessage) appendPadding(params *MessageParams) {
panic("please fix the padding algorithm before releasing new version")
}
buf := make([]byte, padSize)
randomize(buf[1:]) // change to: err = mrand.Read(buf[1:])
randomize(buf[1:])
buf[0] = byte(padSize)
if params.Padding != nil {
copy(buf[1:], params.Padding)
@ -208,7 +208,10 @@ func (msg *SentMessage) encryptSymmetric(key []byte) (salt []byte, nonce []byte,
_, err = crand.Read(nonce)
if err != nil {
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)
return salt, nonce, nil
}

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

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

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

@ -28,11 +28,11 @@ var topicStringTests = []struct {
{topic: TopicType{0xf2, 0x6e, 0x77, 0x79}, str: "0xf26e7779"},
}
func TestTopicString(x *testing.T) {
func TestTopicString(t *testing.T) {
for i, tst := range topicStringTests {
s := tst.topic.String()
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},
}
func TestBytesToTopic(x *testing.T) {
func TestBytesToTopic(t *testing.T) {
for i, tst := range bytesToTopicTests {
t := BytesToTopic(tst.data)
if t != tst.topic {
x.Errorf("failed test %d: have %v, want %v.", i, t, tst.topic)
top := BytesToTopic(tst.data)
if top != 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")},
}
func TestUnmarshalTestsGood(x *testing.T) {
func TestUnmarshalTestsGood(t *testing.T) {
for i, tst := range unmarshalTestsGood {
var t TopicType
err := t.UnmarshalJSON(tst.data)
var top TopicType
err := top.UnmarshalJSON(tst.data)
if err != nil {
x.Errorf("failed test %d. input: %v.", i, tst.data)
} else if t != tst.topic {
x.Errorf("failed test %d: have %v, want %v.", i, t, tst.topic)
t.Fatalf("failed test %d. input: %v.", i, tst.data)
} else if top != 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
for i, tst := range unmarshalTestsBad {
var t TopicType
err := t.UnmarshalJSON(tst.data)
var top TopicType
err := top.UnmarshalJSON(tst.data)
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
for i, tst := range unmarshalTestsUgly {
var t TopicType
err := t.UnmarshalJSON(tst.data)
var top TopicType
err := top.UnmarshalJSON(tst.data)
if err != nil {
x.Errorf("failed test %d. input: %v.", i, tst.data)
} else if t == tst.topic {
x.Errorf("failed test %d: have %v, want %v.", i, t, tst.topic)
t.Fatalf("failed test %d. input: %v.", i, tst.data)
} else if top == tst.topic {
t.Fatalf("failed test %d: have %v, want %v.", i, top, tst.topic)
}
}
}

@ -177,12 +177,13 @@ func (w *Whisper) GetIdentity(pubKey string) *ecdsa.PrivateKey {
}
func (w *Whisper) GenerateSymKey(name string) error {
buf := make([]byte, aesKeyLength*2)
_, err := crand.Read(buf) // todo: check how safe is this function
const size = aesKeyLength * 2
buf := make([]byte, size)
_, err := crand.Read(buf)
if err != nil {
return err
} 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]
@ -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
// from the whisper network.
func (w *Whisper) Watch(f *Filter) int {
func (w *Whisper) Watch(f *Filter) uint32 {
return w.filters.Install(f)
}
func (w *Whisper) GetFilter(id int) *Filter {
func (w *Whisper) GetFilter(id uint32) *Filter {
return w.filters.Get(id)
}
// Unwatch removes an installed message handler.
func (w *Whisper) Unwatch(id int) {
func (w *Whisper) Unwatch(id uint32) {
w.filters.Uninstall(id)
}
@ -404,7 +405,7 @@ func (wh *Whisper) add(envelope *Envelope) error {
return fmt.Errorf("oversized Version")
}
if len(envelope.AESNonce) > 12 {
if len(envelope.AESNonce) > AESNonceMaxLength {
// the standard AES GSM nonce size is 12,
// but const gcmStandardNonceSize cannot be accessed directly
return fmt.Errorf("oversized AESNonce")
@ -507,7 +508,7 @@ func (w *Whisper) Envelopes() []*Envelope {
}
// 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)
w.poolMu.RLock()
defer w.poolMu.RUnlock()

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

Loading…
Cancel
Save