Skip to content

Commit 4020258

Browse files
committed
Merge pull request bnb-chain#718 from karalabe/whisper-cleanup
Whisper cleanup, part 2
2 parents d3ed328 + 4afc22b commit 4020258

16 files changed

Lines changed: 899 additions & 356 deletions

‎ui/qt/qwhisper/whisper.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ func (self *Whisper) Post(payload []string, to, from string, topics []string, pr
4141
TTL: time.Duration(ttl) * time.Second,
4242
To: crypto.ToECDSAPub(common.FromHex(to)),
4343
From: key,
44-
Topics: whisper.TopicsFromString(topics...),
44+
Topics: whisper.NewTopicsFromStrings(topics...),
4545
})
4646

4747
if err != nil {
@@ -106,7 +106,7 @@ func filterFromMap(opts map[string]interface{}) (f whisper.Filter) {
106106
if topicList, ok := opts["topics"].(*qml.List); ok {
107107
var topics []string
108108
topicList.Convert(&topics)
109-
f.Topics = whisper.TopicsFromString(topics...)
109+
f.Topics = whisper.NewTopicsFromStrings(topics...)
110110
}
111111

112112
return

‎whisper/envelope.go‎

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,16 @@ import (
2020
type Envelope struct {
2121
Expiry uint32 // Whisper protocol specifies int32, really should be int64
2222
TTL uint32 // ^^^^^^
23-
Topics [][]byte
23+
Topics []Topic
2424
Data []byte
2525
Nonce uint32
2626

27-
hash common.Hash
27+
hash common.Hash // Cached hash of the envelope to avoid rehashing every time
2828
}
2929

3030
// NewEnvelope wraps a Whisper message with expiration and destination data
3131
// included into an envelope for network forwarding.
32-
func NewEnvelope(ttl time.Duration, topics [][]byte, msg *Message) *Envelope {
32+
func NewEnvelope(ttl time.Duration, topics []Topic, msg *Message) *Envelope {
3333
return &Envelope{
3434
Expiry: uint32(time.Now().Add(ttl).Unix()),
3535
TTL: uint32(ttl.Seconds()),
@@ -59,16 +59,6 @@ func (self *Envelope) Seal(pow time.Duration) {
5959
}
6060
}
6161

62-
// valid checks whether the claimed proof of work was indeed executed.
63-
// TODO: Is this really useful? Isn't this always true?
64-
func (self *Envelope) valid() bool {
65-
d := make([]byte, 64)
66-
copy(d[:32], self.rlpWithoutNonce())
67-
binary.BigEndian.PutUint32(d[60:], self.Nonce)
68-
69-
return common.FirstBitSet(common.BigD(crypto.Sha3(d))) > 0
70-
}
71-
7262
// rlpWithoutNonce returns the RLP encoded envelope contents, except the nonce.
7363
func (self *Envelope) rlpWithoutNonce() []byte {
7464
enc, _ := rlp.EncodeToBytes([]interface{}{self.Expiry, self.TTL, self.Topics, self.Data})
@@ -85,20 +75,19 @@ func (self *Envelope) Open(key *ecdsa.PrivateKey) (msg *Message, err error) {
8575
}
8676
data = data[1:]
8777

88-
if message.Flags&128 == 128 {
89-
if len(data) < 65 {
90-
return nil, fmt.Errorf("unable to open envelope. First bit set but len(data) < 65")
78+
if message.Flags&signatureFlag == signatureFlag {
79+
if len(data) < signatureLength {
80+
return nil, fmt.Errorf("unable to open envelope. First bit set but len(data) < len(signature)")
9181
}
92-
message.Signature, data = data[:65], data[65:]
82+
message.Signature, data = data[:signatureLength], data[signatureLength:]
9383
}
9484
message.Payload = data
9585

96-
// Short circuit if the encryption was requested
86+
// Decrypt the message, if requested
9787
if key == nil {
9888
return message, nil
9989
}
100-
// Otherwise try to decrypt the message
101-
message.Payload, err = crypto.Decrypt(key, message.Payload)
90+
err = message.decrypt(key)
10291
switch err {
10392
case nil:
10493
return message, nil

‎whisper/filter.go‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
// Contains the message filter for fine grained subscriptions.
2+
13
package whisper
24

35
import "crypto/ecdsa"
46

7+
// Filter is used to subscribe to specific types of whisper messages.
58
type Filter struct {
6-
To *ecdsa.PublicKey
7-
From *ecdsa.PublicKey
8-
Topics [][]byte
9-
Fn func(*Message)
9+
To *ecdsa.PublicKey // Recipient of the message
10+
From *ecdsa.PublicKey // Sender of the message
11+
Topics []Topic // Topics to watch messages on
12+
Fn func(*Message) // Handler in case of a match
1013
}

‎whisper/main.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,10 @@ func selfSend(shh *whisper.Whisper, payload []byte) error {
6969
})
7070
// Wrap the payload and encrypt it
7171
msg := whisper.NewMessage(payload)
72-
envelope, err := msg.Wrap(whisper.DefaultProofOfWork, whisper.Options{
72+
envelope, err := msg.Wrap(whisper.DefaultPoW, whisper.Options{
7373
From: id,
7474
To: &id.PublicKey,
75-
TTL: whisper.DefaultTimeToLive,
75+
TTL: whisper.DefaultTTL,
7676
})
7777
if err != nil {
7878
return fmt.Errorf("failed to seal message: %v", err)

‎whisper/message.go‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,14 @@ type Options struct {
3030
From *ecdsa.PrivateKey
3131
To *ecdsa.PublicKey
3232
TTL time.Duration
33-
Topics [][]byte
33+
Topics []Topic
3434
}
3535

3636
// NewMessage creates and initializes a non-signed, non-encrypted Whisper message.
3737
func NewMessage(payload []byte) *Message {
38-
// Construct an initial flag set: bit #1 = 0 (no signature), rest random
39-
flags := byte(rand.Intn(128))
38+
// Construct an initial flag set: no signature, rest random
39+
flags := byte(rand.Intn(256))
40+
flags &= ^signatureFlag
4041

4142
// Assemble and return the message
4243
return &Message{
@@ -61,7 +62,7 @@ func NewMessage(payload []byte) *Message {
6162
func (self *Message) Wrap(pow time.Duration, options Options) (*Envelope, error) {
6263
// Use the default TTL if non was specified
6364
if options.TTL == 0 {
64-
options.TTL = DefaultTimeToLive
65+
options.TTL = DefaultTTL
6566
}
6667
// Sign and encrypt the message if requested
6768
if options.From != nil {
@@ -84,7 +85,7 @@ func (self *Message) Wrap(pow time.Duration, options Options) (*Envelope, error)
8485
// sign calculates and sets the cryptographic signature for the message , also
8586
// setting the sign flag.
8687
func (self *Message) sign(key *ecdsa.PrivateKey) (err error) {
87-
self.Flags |= 1 << 7
88+
self.Flags |= signatureFlag
8889
self.Signature, err = crypto.Sign(self.hash(), key)
8990
return
9091
}
@@ -93,6 +94,11 @@ func (self *Message) sign(key *ecdsa.PrivateKey) (err error) {
9394
func (self *Message) Recover() *ecdsa.PublicKey {
9495
defer func() { recover() }() // in case of invalid signature
9596

97+
// Short circuit if no signature is present
98+
if self.Signature == nil {
99+
return nil
100+
}
101+
// Otherwise try and recover the signature
96102
pub, err := crypto.SigToPub(self.hash(), self.Signature)
97103
if err != nil {
98104
glog.V(logger.Error).Infof("Could not get public key from signature: %v", err)
@@ -102,8 +108,14 @@ func (self *Message) Recover() *ecdsa.PublicKey {
102108
}
103109

104110
// encrypt encrypts a message payload with a public key.
105-
func (self *Message) encrypt(to *ecdsa.PublicKey) (err error) {
106-
self.Payload, err = crypto.Encrypt(to, self.Payload)
111+
func (self *Message) encrypt(key *ecdsa.PublicKey) (err error) {
112+
self.Payload, err = crypto.Encrypt(key, self.Payload)
113+
return
114+
}
115+
116+
// decrypt decrypts an encrypted payload with a private key.
117+
func (self *Message) decrypt(key *ecdsa.PrivateKey) (err error) {
118+
self.Payload, err = crypto.Decrypt(key, self.Payload)
107119
return
108120
}
109121

‎whisper/message_test.go‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,11 @@ func TestMessageSimpleWrap(t *testing.T) {
1313
payload := []byte("hello world")
1414

1515
msg := NewMessage(payload)
16-
if _, err := msg.Wrap(DefaultProofOfWork, Options{}); err != nil {
16+
if _, err := msg.Wrap(DefaultPoW, Options{}); err != nil {
1717
t.Fatalf("failed to wrap message: %v", err)
1818
}
19-
if msg.Flags&128 != 0 {
20-
t.Fatalf("signature flag mismatch: have %d, want %d", (msg.Flags&128)>>7, 0)
19+
if msg.Flags&signatureFlag != 0 {
20+
t.Fatalf("signature flag mismatch: have %d, want %d", msg.Flags&signatureFlag, 0)
2121
}
2222
if len(msg.Signature) != 0 {
2323
t.Fatalf("signature found for simple wrapping: 0x%x", msg.Signature)
@@ -36,13 +36,13 @@ func TestMessageCleartextSignRecover(t *testing.T) {
3636
payload := []byte("hello world")
3737

3838
msg := NewMessage(payload)
39-
if _, err := msg.Wrap(DefaultProofOfWork, Options{
39+
if _, err := msg.Wrap(DefaultPoW, Options{
4040
From: key,
4141
}); err != nil {
4242
t.Fatalf("failed to sign message: %v", err)
4343
}
44-
if msg.Flags&128 != 128 {
45-
t.Fatalf("signature flag mismatch: have %d, want %d", (msg.Flags&128)>>7, 1)
44+
if msg.Flags&signatureFlag != signatureFlag {
45+
t.Fatalf("signature flag mismatch: have %d, want %d", msg.Flags&signatureFlag, signatureFlag)
4646
}
4747
if bytes.Compare(msg.Payload, payload) != 0 {
4848
t.Fatalf("payload mismatch after signing: have 0x%x, want 0x%x", msg.Payload, payload)
@@ -69,14 +69,14 @@ func TestMessageAnonymousEncryptDecrypt(t *testing.T) {
6969
payload := []byte("hello world")
7070

7171
msg := NewMessage(payload)
72-
envelope, err := msg.Wrap(DefaultProofOfWork, Options{
72+
envelope, err := msg.Wrap(DefaultPoW, Options{
7373
To: &key.PublicKey,
7474
})
7575
if err != nil {
7676
t.Fatalf("failed to encrypt message: %v", err)
7777
}
78-
if msg.Flags&128 != 0 {
79-
t.Fatalf("signature flag mismatch: have %d, want %d", (msg.Flags&128)>>7, 0)
78+
if msg.Flags&signatureFlag != 0 {
79+
t.Fatalf("signature flag mismatch: have %d, want %d", msg.Flags&signatureFlag, 0)
8080
}
8181
if len(msg.Signature) != 0 {
8282
t.Fatalf("signature found for anonymous message: 0x%x", msg.Signature)
@@ -104,15 +104,15 @@ func TestMessageFullCrypto(t *testing.T) {
104104

105105
payload := []byte("hello world")
106106
msg := NewMessage(payload)
107-
envelope, err := msg.Wrap(DefaultProofOfWork, Options{
107+
envelope, err := msg.Wrap(DefaultPoW, Options{
108108
From: fromKey,
109109
To: &toKey.PublicKey,
110110
})
111111
if err != nil {
112112
t.Fatalf("failed to encrypt message: %v", err)
113113
}
114-
if msg.Flags&128 != 128 {
115-
t.Fatalf("signature flag mismatch: have %d, want %d", (msg.Flags&128)>>7, 1)
114+
if msg.Flags&signatureFlag != signatureFlag {
115+
t.Fatalf("signature flag mismatch: have %d, want %d", msg.Flags&signatureFlag, signatureFlag)
116116
}
117117
if len(msg.Signature) == 0 {
118118
t.Fatalf("no signature found for signed message")

0 commit comments

Comments
 (0)