whisper: Golint fixes in whisper packages (#16637)

This commit is contained in:
Eli 2018-05-01 23:17:17 -07:00 committed by Guillaume Ballet
parent 1da33028ce
commit 9f6af6f812
8 changed files with 74 additions and 78 deletions

View File

@ -67,7 +67,6 @@ func (sc *Client) SetMaxMessageSize(ctx context.Context, size uint32) error {
} }
// SetMinimumPoW (experimental) sets the minimal PoW required by this node. // SetMinimumPoW (experimental) sets the minimal PoW required by this node.
// This experimental function was introduced for the future dynamic adjustment of // This experimental function was introduced for the future dynamic adjustment of
// PoW requirement. If the node is overwhelmed with messages, it should raise the // PoW requirement. If the node is overwhelmed with messages, it should raise the
// PoW requirement and notify the peers. The new value should be set relative to // PoW requirement and notify the peers. The new value should be set relative to
@ -77,7 +76,7 @@ func (sc *Client) SetMinimumPoW(ctx context.Context, pow float64) error {
return sc.c.CallContext(ctx, &ignored, "shh_setMinPoW", pow) return sc.c.CallContext(ctx, &ignored, "shh_setMinPoW", pow)
} }
// Marks specific peer trusted, which will allow it to send historic (expired) messages. // MarkTrustedPeer marks specific peer trusted, which will allow it to send historic (expired) messages.
// Note This function is not adding new nodes, the node needs to exists as a peer. // Note This function is not adding new nodes, the node needs to exists as a peer.
func (sc *Client) MarkTrustedPeer(ctx context.Context, enode string) error { func (sc *Client) MarkTrustedPeer(ctx context.Context, enode string) error {
var ignored bool var ignored bool

View File

@ -89,7 +89,7 @@ func (api *PublicWhisperAPI) SetMaxMessageSize(ctx context.Context, size uint32)
return true, api.w.SetMaxMessageSize(size) return true, api.w.SetMaxMessageSize(size)
} }
// SetMinPow sets the minimum PoW for a message before it is accepted. // SetMinPoW sets the minimum PoW for a message before it is accepted.
func (api *PublicWhisperAPI) SetMinPoW(ctx context.Context, pow float64) (bool, error) { func (api *PublicWhisperAPI) SetMinPoW(ctx context.Context, pow float64) (bool, error) {
return true, api.w.SetMinimumPoW(pow) return true, api.w.SetMinimumPoW(pow)
} }
@ -142,7 +142,7 @@ func (api *PublicWhisperAPI) GetPublicKey(ctx context.Context, id string) (hexut
return crypto.FromECDSAPub(&key.PublicKey), nil 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. // 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) { func (api *PublicWhisperAPI) GetPrivateKey(ctx context.Context, id string) (hexutil.Bytes, error) {
key, err := api.w.GetPrivateKey(id) key, err := api.w.GetPrivateKey(id)

View File

@ -15,7 +15,7 @@
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
/* /*
Package whisper implements the Whisper protocol (version 5). Package whisperv5 implements the Whisper protocol (version 5).
Whisper combines aspects of both DHTs and datagram messaging systems (e.g. UDP). Whisper combines aspects of both DHTs and datagram messaging systems (e.g. UDP).
As such it may be likened and compared to both, not dissimilar to the As such it may be likened and compared to both, not dissimilar to the

View File

@ -33,7 +33,7 @@ import (
"github.com/ethereum/go-ethereum/log" "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 { type MessageParams struct {
TTL uint32 TTL uint32
Src *ecdsa.PrivateKey Src *ecdsa.PrivateKey
@ -86,7 +86,7 @@ func (msg *ReceivedMessage) isAsymmetricEncryption() bool {
return msg.Dst != nil return msg.Dst != nil
} }
// NewMessage creates and initializes a non-signed, non-encrypted Whisper message. // NewSentMessage creates and initializes a non-signed, non-encrypted Whisper message.
func NewSentMessage(params *MessageParams) (*sentMessage, error) { func NewSentMessage(params *MessageParams) (*sentMessage, error) {
msg := sentMessage{} msg := sentMessage{}
msg.Raw = make([]byte, 1, len(params.Payload)+len(params.Padding)+signatureLength+padSizeLimit) msg.Raw = make([]byte, 1, len(params.Payload)+len(params.Padding)+signatureLength+padSizeLimit)
@ -330,7 +330,7 @@ func (msg *ReceivedMessage) extractPadding(end int) (int, bool) {
return paddingSize, true return paddingSize, true
} }
// Recover retrieves the public key of the message signer. // SigToPubKey retrieves the public key of the message signer.
func (msg *ReceivedMessage) SigToPubKey() *ecdsa.PublicKey { func (msg *ReceivedMessage) SigToPubKey() *ecdsa.PublicKey {
defer func() { recover() }() // in case of invalid signature defer func() { recover() }() // in case of invalid signature

View File

@ -27,7 +27,7 @@ import (
set "gopkg.in/fatih/set.v0" set "gopkg.in/fatih/set.v0"
) )
// peer represents a whisper protocol peer connection. // Peer represents a whisper protocol peer connection.
type Peer struct { type Peer struct {
host *Whisper host *Whisper
peer *p2p.Peer peer *p2p.Peer
@ -53,51 +53,51 @@ func newPeer(host *Whisper, remote *p2p.Peer, rw p2p.MsgReadWriter) *Peer {
// start initiates the peer updater, periodically broadcasting the whisper packets // start initiates the peer updater, periodically broadcasting the whisper packets
// into the network. // into the network.
func (p *Peer) start() { func (peer *Peer) start() {
go p.update() go peer.update()
log.Trace("start", "peer", p.ID()) log.Trace("start", "peer", peer.ID())
} }
// stop terminates the peer updater, stopping message forwarding to it. // stop terminates the peer updater, stopping message forwarding to it.
func (p *Peer) stop() { func (peer *Peer) stop() {
close(p.quit) close(peer.quit)
log.Trace("stop", "peer", p.ID()) log.Trace("stop", "peer", peer.ID())
} }
// handshake sends the protocol initiation status message to the remote peer and // handshake sends the protocol initiation status message to the remote peer and
// verifies the remote status too. // verifies the remote status too.
func (p *Peer) handshake() error { func (peer *Peer) handshake() error {
// Send the handshake status message asynchronously // Send the handshake status message asynchronously
errc := make(chan error, 1) errc := make(chan error, 1)
go func() { go func() {
errc <- p2p.Send(p.ws, statusCode, ProtocolVersion) errc <- p2p.Send(peer.ws, statusCode, ProtocolVersion)
}() }()
// Fetch the remote status packet and verify protocol match // Fetch the remote status packet and verify protocol match
packet, err := p.ws.ReadMsg() packet, err := peer.ws.ReadMsg()
if err != nil { if err != nil {
return err return err
} }
if packet.Code != statusCode { 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)) s := rlp.NewStream(packet.Payload, uint64(packet.Size))
peerVersion, err := s.Uint() peerVersion, err := s.Uint()
if err != nil { 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)
} }
if peerVersion != ProtocolVersion { 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)
} }
// Wait until out own status is consumed too // Wait until out own status is consumed too
if err := <-errc; err != nil { 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 return nil
} }
// update executes periodic operations on the peer, including message transmission // update executes periodic operations on the peer, including message transmission
// and expiration. // and expiration.
func (p *Peer) update() { func (peer *Peer) update() {
// Start the tickers for the updates // Start the tickers for the updates
expire := time.NewTicker(expirationCycle) expire := time.NewTicker(expirationCycle)
transmit := time.NewTicker(transmissionCycle) transmit := time.NewTicker(transmissionCycle)
@ -106,15 +106,15 @@ func (p *Peer) update() {
for { for {
select { select {
case <-expire.C: case <-expire.C:
p.expire() peer.expire()
case <-transmit.C: case <-transmit.C:
if err := p.broadcast(); err != nil { if err := peer.broadcast(); err != nil {
log.Trace("broadcast failed", "reason", err, "peer", p.ID()) log.Trace("broadcast failed", "reason", err, "peer", peer.ID())
return return
} }
case <-p.quit: case <-peer.quit:
return return
} }
} }
@ -148,16 +148,16 @@ func (peer *Peer) expire() {
// broadcast iterates over the collection of envelopes and transmits yet unknown // broadcast iterates over the collection of envelopes and transmits yet unknown
// ones over the network. // ones over the network.
func (p *Peer) broadcast() error { func (peer *Peer) broadcast() error {
var cnt int var cnt int
envelopes := p.host.Envelopes() envelopes := peer.host.Envelopes()
for _, envelope := range envelopes { for _, envelope := range envelopes {
if !p.marked(envelope) { if !peer.marked(envelope) {
err := p2p.Send(p.ws, messagesCode, envelope) err := p2p.Send(peer.ws, messagesCode, envelope)
if err != nil { if err != nil {
return err return err
} else { } else {
p.mark(envelope) peer.mark(envelope)
cnt++ cnt++
} }
} }
@ -168,7 +168,7 @@ func (p *Peer) broadcast() error {
return nil return nil
} }
func (p *Peer) ID() []byte { func (peer *Peer) ID() []byte {
id := p.peer.ID() id := peer.peer.ID()
return id[:] return id[:]
} }

View File

@ -32,7 +32,7 @@ import (
"github.com/ethereum/go-ethereum/p2p/nat" "github.com/ethereum/go-ethereum/p2p/nat"
) )
var keys []string = []string{ var keys = []string{
"d49dcf37238dc8a7aac57dc61b9fee68f0a97f062968978b9fafa7d1033d03a9", "d49dcf37238dc8a7aac57dc61b9fee68f0a97f062968978b9fafa7d1033d03a9",
"73fd6143c48e80ed3c56ea159fe7494a0b6b393a392227b422f4c3e8f1b54f98", "73fd6143c48e80ed3c56ea159fe7494a0b6b393a392227b422f4c3e8f1b54f98",
"119dd32adb1daa7a4c7bf77f847fb28730785aa92947edf42fdd997b54de40dc", "119dd32adb1daa7a4c7bf77f847fb28730785aa92947edf42fdd997b54de40dc",
@ -84,9 +84,9 @@ type TestNode struct {
var result TestData var result TestData
var nodes [NumNodes]*TestNode var nodes [NumNodes]*TestNode
var sharedKey []byte = []byte("some arbitrary data here") var sharedKey = []byte("some arbitrary data here")
var sharedTopic TopicType = TopicType{0xF, 0x1, 0x2, 0} var sharedTopic TopicType = TopicType{0xF, 0x1, 0x2, 0}
var expectedMessage []byte = []byte("per rectum ad astra") var expectedMessage = []byte("per rectum ad astra")
// This test does the following: // This test does the following:
// 1. creates a chain of whisper nodes, // 1. creates a chain of whisper nodes,

View File

@ -23,7 +23,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil" "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 // 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. // SHA3 hash of some arbitrary data given by the original author of the message.
type TopicType [TopicLength]byte type TopicType [TopicLength]byte

View File

@ -469,18 +469,18 @@ func (w *Whisper) Stop() error {
// HandlePeer is called by the underlying P2P layer when the whisper sub-protocol // HandlePeer is called by the underlying P2P layer when the whisper sub-protocol
// connection is negotiated. // connection is negotiated.
func (wh *Whisper) HandlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error { func (w *Whisper) HandlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
// Create the new peer and start tracking it // Create the new peer and start tracking it
whisperPeer := newPeer(wh, peer, rw) whisperPeer := newPeer(w, peer, rw)
wh.peerMu.Lock() w.peerMu.Lock()
wh.peers[whisperPeer] = struct{}{} w.peers[whisperPeer] = struct{}{}
wh.peerMu.Unlock() w.peerMu.Unlock()
defer func() { defer func() {
wh.peerMu.Lock() w.peerMu.Lock()
delete(wh.peers, whisperPeer) delete(w.peers, whisperPeer)
wh.peerMu.Unlock() w.peerMu.Unlock()
}() }()
// Run the peer handshake and state updates // Run the peer handshake and state updates
@ -490,11 +490,11 @@ func (wh *Whisper) HandlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
whisperPeer.start() whisperPeer.start()
defer whisperPeer.stop() defer whisperPeer.stop()
return wh.runMessageLoop(whisperPeer, rw) return w.runMessageLoop(whisperPeer, rw)
} }
// runMessageLoop reads and processes inbound messages directly to merge into client-global state. // runMessageLoop reads and processes inbound messages directly to merge into client-global state.
func (wh *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error { func (w *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
for { for {
// fetch the next packet // fetch the next packet
packet, err := rw.ReadMsg() packet, err := rw.ReadMsg()
@ -502,7 +502,7 @@ func (wh *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
log.Warn("message loop", "peer", p.peer.ID(), "err", err) log.Warn("message loop", "peer", p.peer.ID(), "err", err)
return err return err
} }
if packet.Size > wh.MaxMessageSize() { if packet.Size > w.MaxMessageSize() {
log.Warn("oversized message received", "peer", p.peer.ID()) log.Warn("oversized message received", "peer", p.peer.ID())
return errors.New("oversized message received") return errors.New("oversized message received")
} }
@ -518,7 +518,7 @@ func (wh *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
log.Warn("failed to decode envelope, peer will be disconnected", "peer", p.peer.ID(), "err", err) log.Warn("failed to decode envelope, peer will be disconnected", "peer", p.peer.ID(), "err", err)
return errors.New("invalid envelope") return errors.New("invalid envelope")
} }
cached, err := wh.add(&envelope) cached, err := w.add(&envelope)
if err != nil { if err != nil {
log.Warn("bad envelope received, peer will be disconnected", "peer", p.peer.ID(), "err", err) log.Warn("bad envelope received, peer will be disconnected", "peer", p.peer.ID(), "err", err)
return errors.New("invalid envelope") return errors.New("invalid envelope")
@ -537,17 +537,17 @@ func (wh *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
log.Warn("failed to decode direct message, peer will be disconnected", "peer", p.peer.ID(), "err", err) log.Warn("failed to decode direct message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
return errors.New("invalid direct message") return errors.New("invalid direct message")
} }
wh.postEvent(&envelope, true) w.postEvent(&envelope, true)
} }
case p2pRequestCode: case p2pRequestCode:
// Must be processed if mail server is implemented. Otherwise ignore. // Must be processed if mail server is implemented. Otherwise ignore.
if wh.mailServer != nil { if w.mailServer != nil {
var request Envelope var request Envelope
if err := packet.Decode(&request); err != nil { if err := packet.Decode(&request); err != nil {
log.Warn("failed to decode p2p request message, peer will be disconnected", "peer", p.peer.ID(), "err", err) log.Warn("failed to decode p2p request message, peer will be disconnected", "peer", p.peer.ID(), "err", err)
return errors.New("invalid p2p request") return errors.New("invalid p2p request")
} }
wh.mailServer.DeliverMail(p, &request) w.mailServer.DeliverMail(p, &request)
} }
default: default:
// New message types might be implemented in the future versions of Whisper. // New message types might be implemented in the future versions of Whisper.
@ -561,29 +561,27 @@ func (wh *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
// add inserts a new envelope into the message pool to be distributed within the // add inserts a new envelope into the message pool to be distributed within the
// whisper network. It also inserts the envelope into the expiration pool at the // whisper network. It also inserts the envelope into the expiration pool at the
// appropriate time-stamp. In case of error, connection should be dropped. // appropriate time-stamp. In case of error, connection should be dropped.
func (wh *Whisper) add(envelope *Envelope) (bool, error) { func (w *Whisper) add(envelope *Envelope) (bool, error) {
now := uint32(time.Now().Unix()) now := uint32(time.Now().Unix())
sent := envelope.Expiry - envelope.TTL sent := envelope.Expiry - envelope.TTL
if sent > now { if sent > now {
if sent-SynchAllowance > now { if sent-SynchAllowance > now {
return false, fmt.Errorf("envelope created in the future [%x]", envelope.Hash()) return false, fmt.Errorf("envelope created in the future [%x]", envelope.Hash())
} else {
// recalculate PoW, adjusted for the time difference, plus one second for latency
envelope.calculatePoW(sent - now + 1)
} }
// recalculate PoW, adjusted for the time difference, plus one second for latency
envelope.calculatePoW(sent - now + 1)
} }
if envelope.Expiry < now { if envelope.Expiry < now {
if envelope.Expiry+SynchAllowance*2 < now { if envelope.Expiry+SynchAllowance*2 < now {
return false, fmt.Errorf("very old message") return false, fmt.Errorf("very old message")
} else {
log.Debug("expired envelope dropped", "hash", envelope.Hash().Hex())
return false, nil // drop envelope without error
} }
log.Debug("expired envelope dropped", "hash", envelope.Hash().Hex())
return false, nil // drop envelope without error
} }
if uint32(envelope.size()) > wh.MaxMessageSize() { if uint32(envelope.size()) > w.MaxMessageSize() {
return false, fmt.Errorf("huge messages are not allowed [%x]", envelope.Hash()) return false, fmt.Errorf("huge messages are not allowed [%x]", envelope.Hash())
} }
@ -598,36 +596,36 @@ func (wh *Whisper) add(envelope *Envelope) (bool, error) {
return false, fmt.Errorf("wrong size of AESNonce: %d bytes [env: %x]", aesNonceSize, envelope.Hash()) return false, fmt.Errorf("wrong size of AESNonce: %d bytes [env: %x]", aesNonceSize, envelope.Hash())
} }
if envelope.PoW() < wh.MinPow() { if envelope.PoW() < w.MinPow() {
log.Debug("envelope with low PoW dropped", "PoW", envelope.PoW(), "hash", envelope.Hash().Hex()) log.Debug("envelope with low PoW dropped", "PoW", envelope.PoW(), "hash", envelope.Hash().Hex())
return false, nil // drop envelope without error return false, nil // drop envelope without error
} }
hash := envelope.Hash() hash := envelope.Hash()
wh.poolMu.Lock() w.poolMu.Lock()
_, alreadyCached := wh.envelopes[hash] _, alreadyCached := w.envelopes[hash]
if !alreadyCached { if !alreadyCached {
wh.envelopes[hash] = envelope w.envelopes[hash] = envelope
if wh.expirations[envelope.Expiry] == nil { if w.expirations[envelope.Expiry] == nil {
wh.expirations[envelope.Expiry] = set.NewNonTS() w.expirations[envelope.Expiry] = set.NewNonTS()
} }
if !wh.expirations[envelope.Expiry].Has(hash) { if !w.expirations[envelope.Expiry].Has(hash) {
wh.expirations[envelope.Expiry].Add(hash) w.expirations[envelope.Expiry].Add(hash)
} }
} }
wh.poolMu.Unlock() w.poolMu.Unlock()
if alreadyCached { if alreadyCached {
log.Trace("whisper envelope already cached", "hash", envelope.Hash().Hex()) log.Trace("whisper envelope already cached", "hash", envelope.Hash().Hex())
} else { } else {
log.Trace("cached whisper envelope", "hash", envelope.Hash().Hex()) log.Trace("cached whisper envelope", "hash", envelope.Hash().Hex())
wh.statsMu.Lock() w.statsMu.Lock()
wh.stats.memoryUsed += envelope.size() w.stats.memoryUsed += envelope.size()
wh.statsMu.Unlock() w.statsMu.Unlock()
wh.postEvent(envelope, false) // notify the local node about the new message w.postEvent(envelope, false) // notify the local node about the new message
if wh.mailServer != nil { if w.mailServer != nil {
wh.mailServer.Archive(envelope) w.mailServer.Archive(envelope)
} }
} }
return true, nil return true, nil
@ -838,9 +836,8 @@ func deriveKeyMaterial(key []byte, version uint64) (derivedKey []byte, err error
// because it's a once in a session experience // because it's a once in a session experience
derivedKey := pbkdf2.Key(key, nil, 65356, aesKeyLength, sha256.New) derivedKey := pbkdf2.Key(key, nil, 65356, aesKeyLength, sha256.New)
return derivedKey, nil return derivedKey, nil
} else {
return nil, unknownVersionError(version)
} }
return nil, unknownVersionError(version)
} }
// GenerateRandomID generates a random string, which is then returned to be used as a key id // GenerateRandomID generates a random string, which is then returned to be used as a key id