Commit 367c329b authored by Guillaume Ballet's avatar Guillaume Ballet Committed by Péter Szilágyi

whisper: remove linter warnings (#15972)

* whisper: fixes warnings from the code linter

* whisper: more non-API-breaking changes

The remaining lint errors are because of auto-generated
files and one is because an exported function has a non-
exported return type. Changing this would break the API,
and will be part of another commit for easier reversal.

* whisper: un-export NewSentMessage to please the linter

This is an API change, which is why it's in its own commit.
This change was initiated after the linter complained that
the returned type wasn't exported. I chose to un-export
the function instead of exporting the type, because that
type is an implementation detail that I would like to
change in the near future to make the code more
readable and with an increased coverage.

* whisper: update gencodec output after upgrading it to new lint standards
parent 2ef3815a
......@@ -601,7 +601,7 @@ func requestExpiredMessagesLoop() {
if err != nil {
utils.Fatalf("Failed to save symmetric key for mail request: %s", err)
}
peerID = extractIdFromEnode(*argEnode)
peerID = extractIDFromEnode(*argEnode)
shh.AllowP2PMessagesFromPeer(peerID)
for {
......@@ -652,7 +652,7 @@ func requestExpiredMessagesLoop() {
}
}
func extractIdFromEnode(s string) []byte {
func extractIDFromEnode(s string) []byte {
n, err := discover.ParseNode(s)
if err != nil {
utils.Fatalf("Failed to parse enode: %s", err)
......
......@@ -36,6 +36,7 @@ const (
filterTimeout = 300 // filters are considered timeout out after filterTimeout seconds
)
// List of errors
var (
ErrSymAsym = errors.New("specify either a symmetric or an asymmetric key")
ErrInvalidSymmetricKey = errors.New("invalid symmetric key")
......@@ -116,7 +117,7 @@ func (api *PublicWhisperAPI) SetMaxMessageSize(ctx context.Context, size uint32)
return true, api.w.SetMaxMessageSize(size)
}
// SetMinPow sets the minimum PoW, and notifies the peers.
// SetMinPoW sets the minimum PoW, and notifies the peers.
func (api *PublicWhisperAPI) SetMinPoW(ctx context.Context, pow float64) (bool, error) {
return true, api.w.SetMinimumPoW(pow)
}
......@@ -174,7 +175,7 @@ func (api *PublicWhisperAPI) GetPublicKey(ctx context.Context, id string) (hexut
return crypto.FromECDSAPub(&key.PublicKey), nil
}
// GetPublicKey returns the private key associated with the given key. The key is the hex
// GetPrivateKey returns the private key associated with the given key. The key is the hex
// encoded representation of a key in the form specified in section 4.3.6 of ANSI X9.62.
func (api *PublicWhisperAPI) GetPrivateKey(ctx context.Context, id string) (hexutil.Bytes, error) {
key, err := api.w.GetPrivateKey(id)
......@@ -291,7 +292,7 @@ func (api *PublicWhisperAPI) Post(ctx context.Context, req NewMessage) (bool, er
}
// encrypt and sent message
whisperMsg, err := NewSentMessage(params)
whisperMsg, err := newSentMessage(params)
if err != nil {
return false, err
}
......
......@@ -39,7 +39,7 @@ func BenchmarkEncryptionSym(b *testing.B) {
}
for i := 0; i < b.N; i++ {
msg, _ := NewSentMessage(params)
msg, _ := newSentMessage(params)
_, err := msg.Wrap(params)
if err != nil {
b.Errorf("failed Wrap with seed %d: %s.", seed, err)
......@@ -64,7 +64,7 @@ func BenchmarkEncryptionAsym(b *testing.B) {
params.Dst = &key.PublicKey
for i := 0; i < b.N; i++ {
msg, _ := NewSentMessage(params)
msg, _ := newSentMessage(params)
_, err := msg.Wrap(params)
if err != nil {
b.Fatalf("failed Wrap with seed %d: %s.", seed, err)
......@@ -79,7 +79,7 @@ func BenchmarkDecryptionSymValid(b *testing.B) {
if err != nil {
b.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, _ := NewSentMessage(params)
msg, _ := newSentMessage(params)
env, err := msg.Wrap(params)
if err != nil {
b.Fatalf("failed Wrap with seed %d: %s.", seed, err)
......@@ -101,7 +101,7 @@ func BenchmarkDecryptionSymInvalid(b *testing.B) {
if err != nil {
b.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, _ := NewSentMessage(params)
msg, _ := newSentMessage(params)
env, err := msg.Wrap(params)
if err != nil {
b.Fatalf("failed Wrap with seed %d: %s.", seed, err)
......@@ -130,7 +130,7 @@ func BenchmarkDecryptionAsymValid(b *testing.B) {
f := Filter{KeyAsym: key}
params.KeySym = nil
params.Dst = &key.PublicKey
msg, _ := NewSentMessage(params)
msg, _ := newSentMessage(params)
env, err := msg.Wrap(params)
if err != nil {
b.Fatalf("failed Wrap with seed %d: %s.", seed, err)
......@@ -157,7 +157,7 @@ func BenchmarkDecryptionAsymInvalid(b *testing.B) {
}
params.KeySym = nil
params.Dst = &key.PublicKey
msg, _ := NewSentMessage(params)
msg, _ := newSentMessage(params)
env, err := msg.Wrap(params)
if err != nil {
b.Fatalf("failed Wrap with seed %d: %s.", seed, err)
......@@ -199,7 +199,7 @@ func BenchmarkPoW(b *testing.B) {
for i := 0; i < b.N; i++ {
increment(params.Payload)
msg, _ := NewSentMessage(params)
msg, _ := newSentMessage(params)
_, err := msg.Wrap(params)
if err != nil {
b.Fatalf("failed Wrap with seed %d: %s.", seed, err)
......
......@@ -16,11 +16,13 @@
package whisperv6
// Config represents the configuration state of a whisper node.
type Config struct {
MaxMessageSize uint32 `toml:",omitempty"`
MinimumAcceptedPOW float64 `toml:",omitempty"`
}
// DefaultConfig represents (shocker!) the default configuration.
var DefaultConfig = Config{
MaxMessageSize: DefaultMaxMessageSize,
MinimumAcceptedPOW: DefaultMinimumPoW,
......
......@@ -27,6 +27,9 @@ Whisper is a pure identity-based messaging system. Whisper provides a low-level
or prejudiced by the low-level hardware attributes and characteristics,
particularly the notion of singular endpoints.
*/
// Contains the Whisper protocol constant definitions
package whisperv6
import (
......@@ -34,10 +37,11 @@ import (
"time"
)
// Whisper protocol parameters
const (
ProtocolVersion = uint64(6)
ProtocolVersionStr = "6.0"
ProtocolName = "shh"
ProtocolVersion = uint64(6) // Protocol version number
ProtocolVersionStr = "6.0" // The same, as a string
ProtocolName = "shh" // Nickname of the protocol in geth
// whisper protocol message codes, according to EIP-627
statusCode = 0 // used by whisper protocol
......@@ -55,7 +59,7 @@ const (
signatureLength = 65 // in bytes
aesKeyLength = 32 // in bytes
AESNonceLength = 12 // in bytes
keyIdSize = 32 // in bytes
keyIDSize = 32 // in bytes
bloomFilterSize = 64 // in bytes
EnvelopeHeaderLength = 20
......
......@@ -115,6 +115,8 @@ func (e *Envelope) Seal(options *MessageParams) error {
return nil
}
// PoW computes (if necessary) and returns the proof of work target
// of the envelope.
func (e *Envelope) PoW() float64 {
if e.pow == 0 {
e.calculatePoW(0)
......
......@@ -45,7 +45,7 @@ func TestEnvelopeOpenAcceptsOnlyOneKeyTypeInFilter(t *testing.T) {
mrand.Read(params.Payload)
msg, err := NewSentMessage(&params)
msg, err := newSentMessage(&params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......
......@@ -26,6 +26,7 @@ import (
"github.com/ethereum/go-ethereum/log"
)
// Filter represents a Whisper message filter
type Filter struct {
Src *ecdsa.PublicKey // Sender of the message
KeyAsym *ecdsa.PrivateKey // Private Key of recipient
......@@ -39,12 +40,14 @@ type Filter struct {
mutex sync.RWMutex
}
// Filters represents a collection of filters
type Filters struct {
watchers map[string]*Filter
whisper *Whisper
mutex sync.RWMutex
}
// NewFilters returns a newly created filter collection
func NewFilters(w *Whisper) *Filters {
return &Filters{
watchers: make(map[string]*Filter),
......@@ -52,6 +55,7 @@ func NewFilters(w *Whisper) *Filters {
}
}
// Install will add a new filter to the filter collection
func (fs *Filters) Install(watcher *Filter) (string, error) {
if watcher.KeySym != nil && watcher.KeyAsym != nil {
return "", fmt.Errorf("filters must choose between symmetric and asymmetric keys")
......@@ -81,6 +85,8 @@ func (fs *Filters) Install(watcher *Filter) (string, error) {
return id, err
}
// Uninstall will remove a filter whose id has been specified from
// the filter collection
func (fs *Filters) Uninstall(id string) bool {
fs.mutex.Lock()
defer fs.mutex.Unlock()
......@@ -91,12 +97,15 @@ func (fs *Filters) Uninstall(id string) bool {
return false
}
// Get returns a filter from the collection with a specific ID
func (fs *Filters) Get(id string) *Filter {
fs.mutex.RLock()
defer fs.mutex.RUnlock()
return fs.watchers[id]
}
// NotifyWatchers notifies any filter that has declared interest
// for the envelope's topic.
func (fs *Filters) NotifyWatchers(env *Envelope, p2pMessage bool) {
var msg *ReceivedMessage
......@@ -140,9 +149,9 @@ func (f *Filter) processEnvelope(env *Envelope) *ReceivedMessage {
msg := env.Open(f)
if msg != nil {
return msg
} else {
log.Trace("processing envelope: failed to open", "hash", env.Hash().Hex())
}
log.Trace("processing envelope: failed to open", "hash", env.Hash().Hex())
} else {
log.Trace("processing envelope: does not match", "hash", env.Hash().Hex())
}
......@@ -157,6 +166,8 @@ func (f *Filter) expectsSymmetricEncryption() bool {
return f.KeySym != nil
}
// Trigger adds a yet-unknown message to the filter's list of
// received messages.
func (f *Filter) Trigger(msg *ReceivedMessage) {
f.mutex.Lock()
defer f.mutex.Unlock()
......@@ -166,6 +177,8 @@ func (f *Filter) Trigger(msg *ReceivedMessage) {
}
}
// Retrieve will return the list of all received messages associated
// to a filter.
func (f *Filter) Retrieve() (all []*ReceivedMessage) {
f.mutex.Lock()
defer f.mutex.Unlock()
......@@ -195,7 +208,7 @@ func (f *Filter) MatchMessage(msg *ReceivedMessage) bool {
return false
}
// MatchEvelope checks if it's worth decrypting the message. If
// MatchEnvelope checks if it's worth decrypting the message. If
// it returns `true`, client code is expected to attempt decrypting
// the message and subsequently call MatchMessage.
func (f *Filter) MatchEnvelope(envelope *Envelope) bool {
......@@ -206,6 +219,7 @@ func (f *Filter) MatchEnvelope(envelope *Envelope) bool {
return f.MatchTopic(envelope.Topic)
}
// MatchTopic checks that the filter captures a given topic.
func (f *Filter) MatchTopic(topic TopicType) bool {
if len(f.Topics) == 0 {
// any topic matches
......@@ -237,6 +251,7 @@ func matchSingleTopic(topic TopicType, bt []byte) bool {
return true
}
// IsPubKeyEqual checks that two public keys are equal
func IsPubKeyEqual(a, b *ecdsa.PublicKey) bool {
if !ValidatePublicKey(a) {
return false
......
......@@ -109,7 +109,7 @@ func TestInstallFilters(t *testing.T) {
t.Fatalf("seed %d: failed to install filter: %s", seed, err)
}
tst[i].id = j
if len(j) != keyIdSize*2 {
if len(j) != keyIDSize*2 {
t.Fatalf("seed %d: wrong filter id size [%d]", seed, len(j))
}
}
......@@ -199,7 +199,7 @@ func TestInstallIdenticalFilters(t *testing.T) {
filter1.Src = &params.Src.PublicKey
filter2.Src = &params.Src.PublicKey
sentMessage, err := NewSentMessage(params)
sentMessage, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -306,7 +306,7 @@ func TestMatchEnvelope(t *testing.T) {
params.Topic[0] = 0xFF // ensure mismatch
// mismatch with pseudo-random data
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -327,7 +327,7 @@ func TestMatchEnvelope(t *testing.T) {
i := mrand.Int() % 4
fsym.Topics[i] = params.Topic[:]
fasym.Topics[i] = params.Topic[:]
msg, err = NewSentMessage(params)
msg, err = newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -372,7 +372,7 @@ func TestMatchEnvelope(t *testing.T) {
}
params.KeySym = nil
params.Dst = &key.PublicKey
msg, err = NewSentMessage(params)
msg, err = newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -453,7 +453,7 @@ func TestMatchMessageSym(t *testing.T) {
params.KeySym = f.KeySym
params.Topic = BytesToTopic(f.Topics[index])
sentMessage, err := NewSentMessage(params)
sentMessage, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -546,7 +546,7 @@ func TestMatchMessageAsym(t *testing.T) {
keySymOrig := params.KeySym
params.KeySym = nil
sentMessage, err := NewSentMessage(params)
sentMessage, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -630,7 +630,7 @@ func generateCompatibeEnvelope(t *testing.T, f *Filter) *Envelope {
params.KeySym = f.KeySym
params.Topic = BytesToTopic(f.Topics[2])
sentMessage, err := NewSentMessage(params)
sentMessage, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -806,7 +806,7 @@ func TestVariableTopics(t *testing.T) {
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......
......@@ -10,6 +10,7 @@ import (
var _ = (*criteriaOverride)(nil)
// MarshalJSON marshals type Criteria to a json string
func (c Criteria) MarshalJSON() ([]byte, error) {
type Criteria struct {
SymKeyID string `json:"symKeyID"`
......@@ -29,6 +30,7 @@ func (c Criteria) MarshalJSON() ([]byte, error) {
return json.Marshal(&enc)
}
// UnmarshalJSON unmarshals type Criteria to a json string
func (c *Criteria) UnmarshalJSON(input []byte) error {
type Criteria struct {
SymKeyID *string `json:"symKeyID"`
......
......@@ -10,6 +10,7 @@ import (
var _ = (*messageOverride)(nil)
// MarshalJSON marshals type Message to a json string
func (m Message) MarshalJSON() ([]byte, error) {
type Message struct {
Sig hexutil.Bytes `json:"sig,omitempty"`
......@@ -35,6 +36,7 @@ func (m Message) MarshalJSON() ([]byte, error) {
return json.Marshal(&enc)
}
// UnmarshalJSON unmarshals type Message to a json string
func (m *Message) UnmarshalJSON(input []byte) error {
type Message struct {
Sig *hexutil.Bytes `json:"sig,omitempty"`
......
......@@ -10,6 +10,7 @@ import (
var _ = (*newMessageOverride)(nil)
// MarshalJSON marshals type NewMessage to a json string
func (n NewMessage) MarshalJSON() ([]byte, error) {
type NewMessage struct {
SymKeyID string `json:"symKeyID"`
......@@ -37,6 +38,7 @@ func (n NewMessage) MarshalJSON() ([]byte, error) {
return json.Marshal(&enc)
}
// UnmarshalJSON unmarshals type NewMessage to a json string
func (n *NewMessage) UnmarshalJSON(input []byte) error {
type NewMessage struct {
SymKeyID *string `json:"symKeyID"`
......
......@@ -33,7 +33,8 @@ import (
"github.com/ethereum/go-ethereum/log"
)
// Options specifies the exact way a message should be wrapped into an Envelope.
// MessageParams specifies the exact way a message should be wrapped
// into an Envelope.
type MessageParams struct {
TTL uint32
Src *ecdsa.PrivateKey
......@@ -86,8 +87,8 @@ func (msg *ReceivedMessage) isAsymmetricEncryption() bool {
return msg.Dst != nil
}
// NewMessage creates and initializes a non-signed, non-encrypted Whisper message.
func NewSentMessage(params *MessageParams) (*sentMessage, error) {
// NewSentMessage creates and initializes a non-signed, non-encrypted Whisper message.
func newSentMessage(params *MessageParams) (*sentMessage, error) {
msg := sentMessage{}
msg.Raw = make([]byte, 1, len(params.Payload)+len(params.Padding)+signatureLength+padSizeLimit)
msg.Raw[0] = 0 // set all the flags to zero
......@@ -341,7 +342,8 @@ func (msg *ReceivedMessage) extractPadding(end int) (int, bool) {
return paddingSize, true
}
// Recover retrieves the public key of the message signer.
// SigToPubKey returns the public key associated to the message's
// signature.
func (msg *ReceivedMessage) SigToPubKey() *ecdsa.PublicKey {
defer func() { recover() }() // in case of invalid signature
......
......@@ -70,7 +70,7 @@ func singleMessageTest(t *testing.T, symmetric bool) {
text := make([]byte, 0, 512)
text = append(text, params.Payload...)
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -128,7 +128,7 @@ func TestMessageWrap(t *testing.T) {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -146,7 +146,7 @@ func TestMessageWrap(t *testing.T) {
}
// set PoW target too high, expect error
msg2, err := NewSentMessage(params)
msg2, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -169,7 +169,7 @@ func TestMessageSeal(t *testing.T) {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -231,7 +231,7 @@ func singleEnvelopeOpenTest(t *testing.T, symmetric bool) {
text := make([]byte, 0, 512)
text = append(text, params.Payload...)
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -286,7 +286,7 @@ func TestEncryptWithZeroKey(t *testing.T) {
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -300,7 +300,7 @@ func TestEncryptWithZeroKey(t *testing.T) {
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err = NewSentMessage(params)
msg, err = newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -314,7 +314,7 @@ func TestEncryptWithZeroKey(t *testing.T) {
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err = NewSentMessage(params)
msg, err = newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -332,7 +332,7 @@ func TestRlpEncode(t *testing.T) {
if err != nil {
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
}
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -376,7 +376,7 @@ func singlePaddingTest(t *testing.T, padSize int) {
if n != padSize {
t.Fatalf("padding is not copied (seed %d): %s", seed, err)
}
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......
......@@ -28,7 +28,7 @@ import (
set "gopkg.in/fatih/set.v0"
)
// peer represents a whisper protocol peer connection.
// Peer represents a whisper protocol peer connection.
type Peer struct {
host *Whisper
peer *p2p.Peer
......@@ -58,48 +58,48 @@ func newPeer(host *Whisper, remote *p2p.Peer, rw p2p.MsgReadWriter) *Peer {
// start initiates the peer updater, periodically broadcasting the whisper packets
// into the network.
func (p *Peer) start() {
go p.update()
log.Trace("start", "peer", p.ID())
func (peer *Peer) start() {
go peer.update()
log.Trace("start", "peer", peer.ID())
}
// stop terminates the peer updater, stopping message forwarding to it.
func (p *Peer) stop() {
close(p.quit)
log.Trace("stop", "peer", p.ID())
func (peer *Peer) stop() {
close(peer.quit)
log.Trace("stop", "peer", peer.ID())
}
// handshake sends the protocol initiation status message to the remote peer and
// verifies the remote status too.
func (p *Peer) handshake() error {
func (peer *Peer) handshake() error {
// Send the handshake status message asynchronously
errc := make(chan error, 1)
go func() {
pow := p.host.MinPow()
pow := peer.host.MinPow()
powConverted := math.Float64bits(pow)
bloom := p.host.BloomFilter()
errc <- p2p.SendItems(p.ws, statusCode, ProtocolVersion, powConverted, bloom)
bloom := peer.host.BloomFilter()
errc <- p2p.SendItems(peer.ws, statusCode, ProtocolVersion, powConverted, bloom)
}()
// Fetch the remote status packet and verify protocol match
packet, err := p.ws.ReadMsg()
packet, err := peer.ws.ReadMsg()
if err != nil {
return err
}
if packet.Code != statusCode {
return fmt.Errorf("peer [%x] sent packet %x before status packet", p.ID(), packet.Code)
return fmt.Errorf("peer [%x] sent packet %x before status packet", peer.ID(), packet.Code)
}
s := rlp.NewStream(packet.Payload, uint64(packet.Size))
_, err = s.List()
if err != nil {
return fmt.Errorf("peer [%x] sent bad status message: %v", p.ID(), err)
return fmt.Errorf("peer [%x] sent bad status message: %v", peer.ID(), err)
}
peerVersion, err := s.Uint()
if err != nil {
return fmt.Errorf("peer [%x] sent bad status message (unable to decode version): %v", p.ID(), err)
return fmt.Errorf("peer [%x] sent bad status message (unable to decode version): %v", peer.ID(), err)
}
if peerVersion != ProtocolVersion {
return fmt.Errorf("peer [%x]: protocol version mismatch %d != %d", p.ID(), peerVersion, ProtocolVersion)
return fmt.Errorf("peer [%x]: protocol version mismatch %d != %d", peer.ID(), peerVersion, ProtocolVersion)
}
// only version is mandatory, subsequent parameters are optional
......@@ -107,34 +107,34 @@ func (p *Peer) handshake() error {
if err == nil {
pow := math.Float64frombits(powRaw)
if math.IsInf(pow, 0) || math.IsNaN(pow) || pow < 0.0 {
return fmt.Errorf("peer [%x] sent bad status message: invalid pow", p.ID())
return fmt.Errorf("peer [%x] sent bad status message: invalid pow", peer.ID())
}
p.powRequirement = pow
peer.powRequirement = pow
var bloom []byte
err = s.Decode(&bloom)
if err == nil {
sz := len(bloom)
if sz != bloomFilterSize && sz != 0 {
return fmt.Errorf("peer [%x] sent bad status message: wrong bloom filter size %d", p.ID(), sz)
return fmt.Errorf("peer [%x] sent bad status message: wrong bloom filter size %d", peer.ID(), sz)
}
if isFullNode(bloom) {
p.bloomFilter = nil
peer.bloomFilter = nil
} else {
p.bloomFilter = bloom
peer.bloomFilter = bloom
}
}
}
if err := <-errc; err != nil {
return fmt.Errorf("peer [%x] failed to send status packet: %v", p.ID(), err)
return fmt.Errorf("peer [%x] failed to send status packet: %v", peer.ID(), err)
}
return nil
}
// update executes periodic operations on the peer, including message transmission
// and expiration.
func (p *Peer) update() {
func (peer *Peer) update() {
// Start the tickers for the updates
expire := time.NewTicker(expirationCycle)
transmit := time.NewTicker(transmissionCycle)
......@@ -143,15 +143,15 @@ func (p *Peer) update() {
for {
select {
case <-expire.C:
p.expire()
peer.expire()
case <-transmit.C:
if err := p.broadcast(); err != nil {
log.Trace("broadcast failed", "reason", err, "peer", p.ID())
if err := peer.broadcast(); err != nil {
log.Trace("broadcast failed", "reason", err, "peer", peer.ID())
return
}
case <-p.quit:
case <-peer.quit:
return
}
}
......@@ -185,24 +185,24 @@ func (peer *Peer) expire() {
// broadcast iterates over the collection of envelopes and transmits yet unknown
// ones over the network.
func (p *Peer) broadcast() error {
envelopes := p.host.Envelopes()
func (peer *Peer) broadcast() error {
envelopes := peer.host.Envelopes()
bundle := make([]*Envelope, 0, len(envelopes))
for _, envelope := range envelopes {
if !p.marked(envelope) && envelope.PoW() >= p.powRequirement && p.bloomMatch(envelope) {
if !peer.marked(envelope) && envelope.PoW() >= peer.powRequirement && peer.bloomMatch(envelope) {
bundle = append(bundle, envelope)
}
}
if len(bundle) > 0 {
// transmit the batch of envelopes
if err := p2p.Send(p.ws, messagesCode, bundle); err != nil {
if err := p2p.Send(peer.ws, messagesCode, bundle); err != nil {
return err
}
// mark envelopes only if they were successfully sent
for _, e := range bundle {
p.mark(e)
peer.mark(e)
}
log.Trace("broadcast", "num. messages", len(bundle))
......@@ -210,25 +210,26 @@ func (p *Peer) broadcast() error {
return nil
}
func (p *Peer) ID() []byte {
id := p.peer.ID()
// ID returns a peer's id
func (peer *Peer) ID() []byte {
id := peer.peer.ID()
return id[:]
}
func (p *Peer) notifyAboutPowRequirementChange(pow float64) error {
func (peer *Peer) notifyAboutPowRequirementChange(pow float64) error {
i := math.Float64bits(pow)
return p2p.Send(p.ws, powRequirementCode, i)
return p2p.Send(peer.ws, powRequirementCode, i)
}
func (p *Peer) notifyAboutBloomFilterChange(bloom []byte) error {
return p2p.Send(p.ws, bloomFilterExCode, bloom)
func (peer *Peer) notifyAboutBloomFilterChange(bloom []byte) error {
return p2p.Send(peer.ws, bloomFilterExCode, bloom)
}
func (p *Peer) bloomMatch(env *Envelope) bool {
if p.bloomFilter == nil {
func (peer *Peer) bloomMatch(env *Envelope) bool {
if peer.bloomFilter == nil {
// no filter - full node, accepts all envelops
return true
}
return bloomFilterMatch(p.bloomFilter, env.Bloom())
return bloomFilterMatch(peer.bloomFilter, env.Bloom())
}
......@@ -33,7 +33,7 @@ import (
"github.com/ethereum/go-ethereum/p2p/nat"
)
var keys []string = []string{
var keys = []string{
"d49dcf37238dc8a7aac57dc61b9fee68f0a97f062968978b9fafa7d1033d03a9",
"73fd6143c48e80ed3c56ea159fe7494a0b6b393a392227b422f4c3e8f1b54f98",
"119dd32adb1daa7a4c7bf77f847fb28730785aa92947edf42fdd997b54de40dc",
......@@ -80,17 +80,17 @@ type TestNode struct {
shh *Whisper
id *ecdsa.PrivateKey
server *p2p.Server
filerId string
filerID string
}
var result TestData
var nodes [NumNodes]*TestNode
var sharedKey []byte = []byte("some arbitrary data here")
var sharedTopic TopicType = TopicType{0xF, 0x1, 0x2, 0}
var expectedMessage []byte = []byte("per rectum ad astra")
var sharedKey = []byte("some arbitrary data here")
var sharedTopic = TopicType{0xF, 0x1, 0x2, 0}
var expectedMessage = []byte("per rectum ad astra")
var masterBloomFilter []byte
var masterPow = 0.00000001
var round int = 1
var round = 1
func TestSimulation(t *testing.T) {
// create a chain of whisper nodes,
......@@ -186,7 +186,7 @@ func initialize(t *testing.T) {
topics = append(topics, sharedTopic)
f := Filter{KeySym: sharedKey}
f.Topics = [][]byte{topics[0][:]}
node.filerId, err = node.shh.Subscribe(&f)
node.filerID, err = node.shh.Subscribe(&f)
if err != nil {
t.Fatalf("failed to install the filter: %s.", err)
}
......@@ -199,9 +199,9 @@ func initialize(t *testing.T) {
name := common.MakeName("whisper-go", "2.0")
var peers []*discover.Node
if i > 0 {
peerNodeId := nodes[i-1].id
peerNodeID := nodes[i-1].id
peerPort := uint16(port - 1)
peerNode := discover.PubkeyID(&peerNodeId.PublicKey)
peerNode := discover.PubkeyID(&peerNodeID.PublicKey)
peer := discover.NewNode(peerNode, ip, peerPort, peerPort)
peers = append(peers, peer)
}
......@@ -238,7 +238,7 @@ func stopServers() {
for i := 0; i < NumNodes; i++ {
n := nodes[i]
if n != nil {
n.shh.Unsubscribe(n.filerId)
n.shh.Unsubscribe(n.filerID)
n.shh.Stop()
n.server.Stop()
}
......@@ -260,9 +260,9 @@ func checkPropagation(t *testing.T, includingNodeZero bool) {
for j := 0; j < iterations; j++ {
for i := first; i < NumNodes; i++ {
f := nodes[i].shh.GetFilter(nodes[i].filerId)
f := nodes[i].shh.GetFilter(nodes[i].filerID)
if f == nil {
t.Fatalf("failed to get filterId %s from node %d, round %d.", nodes[i].filerId, i, round)
t.Fatalf("failed to get filterId %s from node %d, round %d.", nodes[i].filerID, i, round)
}
mail := f.Retrieve()
......@@ -281,7 +281,7 @@ func checkPropagation(t *testing.T, includingNodeZero bool) {
t.Fatalf("Test was not complete: timeout %d seconds.", iterations*cycle/1000)
if !includingNodeZero {
f := nodes[0].shh.GetFilter(nodes[0].filerId)
f := nodes[0].shh.GetFilter(nodes[0].filerID)
if f != nil {
t.Fatalf("node zero received a message with low PoW.")
}
......@@ -348,7 +348,7 @@ func sendMsg(t *testing.T, expected bool, id int) {
opt.Payload = opt.Payload[1:]
}
msg, err := NewSentMessage(&opt)
msg, err := newSentMessage(&opt)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -372,7 +372,7 @@ func TestPeerBasic(t *testing.T) {
}
params.PoW = 0.001
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......
......@@ -23,11 +23,13 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
)
// Topic represents a cryptographically secure, probabilistic partial
// TopicType represents a cryptographically secure, probabilistic partial
// classifications of a message, determined as the first (left) 4 bytes of the
// SHA3 hash of some arbitrary data given by the original author of the message.
type TopicType [TopicLength]byte
// BytesToTopic converts from the byte array representation of a topic
// into the TopicType type.
func BytesToTopic(b []byte) (t TopicType) {
sz := TopicLength
if x := len(b); x < TopicLength {
......
This diff is collapsed.
......@@ -483,7 +483,7 @@ func TestExpiry(t *testing.T) {
}
params.TTL = 1
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -549,7 +549,7 @@ func TestCustomization(t *testing.T) {
params.Topic = BytesToTopic(f.Topics[2])
params.PoW = smallPoW
params.TTL = 3600 * 24 // one day
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -570,7 +570,7 @@ func TestCustomization(t *testing.T) {
}
params.TTL++
msg, err = NewSentMessage(params)
msg, err = newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -659,7 +659,7 @@ func TestSymmetricSendCycle(t *testing.T) {
params.PoW = filter1.PoW
params.WorkTime = 10
params.TTL = 50
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -737,7 +737,7 @@ func TestSymmetricSendWithoutAKey(t *testing.T) {
params.PoW = filter.PoW
params.WorkTime = 10
params.TTL = 50
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......@@ -803,7 +803,7 @@ func TestSymmetricSendKeyMismatch(t *testing.T) {
params.PoW = filter.PoW
params.WorkTime = 10
params.TTL = 50
msg, err := NewSentMessage(params)
msg, err := newSentMessage(params)
if err != nil {
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
}
......
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