Commit 2dcf75a7 authored by gluk256's avatar gluk256 Committed by Felix Lange

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
parent 671fd94e
...@@ -149,13 +149,13 @@ func (api *PublicWhisperAPI) DeleteSymKey(name string) error { ...@@ -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, ...@@ -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, ...@@ -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 ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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"`
......
This diff is collapsed.
...@@ -40,8 +40,7 @@ func BenchmarkEncryptionSym(b *testing.B) { ...@@ -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) { ...@@ -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) { ...@@ -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) { ...@@ -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) { ...@@ -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) { ...@@ -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) { ...@@ -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) { ...@@ -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
} }
} }
} }
...@@ -46,7 +46,7 @@ const ( ...@@ -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 ( ...@@ -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
......
...@@ -73,7 +73,7 @@ func NewEnvelope(ttl uint32, topic TopicType, salt []byte, aesNonce []byte, msg ...@@ -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) { ...@@ -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
} }
......
...@@ -37,20 +37,20 @@ type Filter struct { ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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
}
if encryptionMethodMatch { func (f *Filter) MatchTopic(topic TopicType) bool {
for _, t := range f.Topics { if len(f.Topics) == 0 {
if t == envelope.Topic { // any topic matches
return true return true
} }
for _, t := range f.Topics {
if t == topic {
return true
} }
} }
return false return false
} }
......
This diff is collapsed.
...@@ -130,7 +130,7 @@ func (msg *SentMessage) appendPadding(params *MessageParams) { ...@@ -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, ...@@ -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
} }
......
...@@ -57,17 +57,15 @@ func generateMessageParams() (*MessageParams, error) { ...@@ -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) { ...@@ -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) { ...@@ -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) { ...@@ -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) { ...@@ -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) { ...@@ -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) { ...@@ -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) { ...@@ -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
} }
} }
} }
...@@ -165,6 +165,9 @@ func (p *Peer) broadcast() error { ...@@ -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
......
...@@ -79,7 +79,7 @@ type TestNode struct { ...@@ -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") ...@@ -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) { ...@@ -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) { ...@@ -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() { ...@@ -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) { ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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) { ...@@ -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
} }
} }
...@@ -28,11 +28,11 @@ var topicStringTests = []struct { ...@@ -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 { ...@@ -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 { ...@@ -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)
} }
} }
} }
...@@ -177,12 +177,13 @@ func (w *Whisper) GetIdentity(pubKey string) *ecdsa.PrivateKey { ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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()
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment