whisper

package
v0.69.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 27, 2021 License: MPL-2.0 Imports: 35 Imported by: 0

README

Whisper

Go implementation of the Whisper specifications

Deprecation Warning!

This package is DEPRECATED and, except for security patches, should not receive any further updates.

Whisper has been forked into Waku. See Go implementation, spec and motivation for more.

Documentation

Index

Constants

View Source
const (
	ProtocolVersion    = uint64(6) // Protocol version number
	ProtocolVersionStr = "6.0"     // The same, as a string
	ProtocolName       = "shh"     // Nickname of the protocol in geth

	NumberOfMessageCodes = 128

	SizeMask = byte(3) // mask used to extract the size of payload size field from the flags

	TopicLength = 4 // in bytes

	BloomFilterSize = 64 // in bytes

	EnvelopeHeaderLength = 20

	MaxMessageSize        = uint32(10 * 1024 * 1024) // maximum accepted size of a message.
	DefaultMaxMessageSize = uint32(1024 * 1024)
	DefaultMinimumPoW     = 0.2

	DefaultTTL           = 50 // seconds
	DefaultSyncAllowance = 10 // seconds

	MaxLimitInSyncMailRequest = 1000

	EnvelopeTimeNotSynced uint = iota + 1
	EnvelopeOtherError

	MaxLimitInMessagesRequest = 1000
)

Whisper protocol parameters

Variables

View Source
var (
	ErrSymAsym              = errors.New("specify either a symmetric or an asymmetric key")
	ErrInvalidSymmetricKey  = errors.New("invalid symmetric key")
	ErrInvalidPublicKey     = errors.New("invalid public key")
	ErrInvalidSigningPubKey = errors.New("invalid signing public key")
	ErrTooLowPoW            = errors.New("message rejected, PoW too low")
	ErrNoTopics             = errors.New("missing topic(s)")
)

List of errors

View Source
var DefaultConfig = Config{
	MaxMessageSize:                        DefaultMaxMessageSize,
	MinimumAcceptedPOW:                    DefaultMinimumPoW,
	RestrictConnectionBetweenLightClients: true,
}

DefaultConfig represents (shocker!) the default configuration.

View Source
var ErrRateLimitExceeded = errors.New("rate limit has been exceeded")

Functions

func BloomFilterMatch

func BloomFilterMatch(filter, sample []byte) bool

func BytesToUintBigEndian

func BytesToUintBigEndian(b []byte) (res uint64)

BytesToUintBigEndian converts the slice to 64-bit unsigned integer.

func CreateMailServerRequestCompletedPayload

func CreateMailServerRequestCompletedPayload(requestID, lastEnvelopeHash common.Hash, cursor []byte) []byte

CreateMailServerRequestCompletedPayload creates a payload representing a successful request to mailserver

func CreateMailServerRequestFailedPayload

func CreateMailServerRequestFailedPayload(requestID common.Hash, err error) []byte

CreateMailServerRequestFailedPayload creates a payload representing a failed request to a mailserver

func GenerateRandomID

func GenerateRandomID() (id string, err error)

GenerateRandomID generates a random string, which is then returned to be used as a key id

func IsPubKeyEqual

func IsPubKeyEqual(a, b *ecdsa.PublicKey) bool

IsPubKeyEqual checks that two public keys are equal

func MakeFullNodeBloom

func MakeFullNodeBloom() []byte

func NewSentMessage

func NewSentMessage(params *MessageParams) (*sentMessage, error)

NewSentMessage creates and initializes a non-signed, non-encrypted Whisper message.

func TopicToBloom

func TopicToBloom(topic TopicType) []byte

TopicToBloom converts the topic (4 bytes) to the bloom filter (64 bytes)

func ValidatePublicKey

func ValidatePublicKey(k *ecdsa.PublicKey) bool

ValidatePublicKey checks the format of the given public key.

Types

type Bridge

type Bridge interface {
	Pipe() (<-chan *Envelope, chan<- *Envelope)
}

type Config

type Config struct {
	MaxMessageSize                        uint32  `toml:",omitempty"`
	MinimumAcceptedPOW                    float64 `toml:",omitempty"`
	RestrictConnectionBetweenLightClients bool    `toml:",omitempty"`
	DisableConfirmations                  bool    `toml:",omitempty"`
}

Config represents the configuration state of a whisper node.

type Criteria

type Criteria struct {
	SymKeyID     string      `json:"symKeyID"`
	PrivateKeyID string      `json:"privateKeyID"`
	Sig          []byte      `json:"sig"`
	MinPow       float64     `json:"minPow"`
	Topics       []TopicType `json:"topics"`
	AllowP2P     bool        `json:"allowP2P"`
}

Criteria holds various filter options for inbound messages.

func (Criteria) MarshalJSON

func (c Criteria) MarshalJSON() ([]byte, error)

MarshalJSON marshals type Criteria to a json string

func (*Criteria) UnmarshalJSON

func (c *Criteria) UnmarshalJSON(input []byte) error

UnmarshalJSON unmarshals type Criteria to a json string

type DropPeerRateLimiterHandler

type DropPeerRateLimiterHandler struct {
	// Tolerance is a number of how many a limit must be exceeded
	// in order to drop a peer.
	Tolerance int64
	// contains filtered or unexported fields
}

func (*DropPeerRateLimiterHandler) ExceedIPLimit

func (h *DropPeerRateLimiterHandler) ExceedIPLimit() error

func (*DropPeerRateLimiterHandler) ExceedPeerLimit

func (h *DropPeerRateLimiterHandler) ExceedPeerLimit() error

type Envelope

type Envelope struct {
	Expiry uint32
	TTL    uint32
	Topic  TopicType
	Data   []byte
	Nonce  uint64
	// contains filtered or unexported fields
}

Envelope represents a clear-text data packet to transmit through the Whisper network. Its contents may or may not be encrypted and signed.

func NewEnvelope

func NewEnvelope(ttl uint32, topic TopicType, msg *sentMessage, now time.Time) *Envelope

NewEnvelope wraps a Whisper message with expiration and destination data included into an envelope for network forwarding.

func (*Envelope) Bloom

func (e *Envelope) Bloom() []byte

Bloom maps 4-bytes Topic into 64-byte bloom filter with 3 bits set (at most).

func (*Envelope) DecodeRLP

func (e *Envelope) DecodeRLP(s *rlp.Stream) error

DecodeRLP decodes an Envelope from an RLP data stream.

func (*Envelope) Hash

func (e *Envelope) Hash() common.Hash

Hash returns the SHA3 hash of the envelope, calculating it if not yet done.

func (*Envelope) Open

func (e *Envelope) Open(watcher *Filter) (msg *ReceivedMessage)

Open tries to decrypt an envelope, and populates the message fields in case of success.

func (*Envelope) OpenAsymmetric

func (e *Envelope) OpenAsymmetric(key *ecdsa.PrivateKey) (*ReceivedMessage, error)

OpenAsymmetric tries to decrypt an envelope, potentially encrypted with a particular key.

func (*Envelope) OpenSymmetric

func (e *Envelope) OpenSymmetric(key []byte) (msg *ReceivedMessage, err error)

OpenSymmetric tries to decrypt an envelope, potentially encrypted with a particular key.

func (*Envelope) PoW

func (e *Envelope) PoW() float64

PoW computes (if necessary) and returns the proof of work target of the envelope.

func (*Envelope) Seal

func (e *Envelope) Seal(options *MessageParams) error

Seal closes the envelope by spending the requested amount of time as a proof of work on hashing the data.

type EnvelopeError

type EnvelopeError struct {
	Hash        common.Hash
	Code        uint
	Description string
}

EnvelopeError code and optional description of the error.

func ErrorToEnvelopeError

func ErrorToEnvelopeError(hash common.Hash, err error) EnvelopeError

ErrorToEnvelopeError converts common golang error into EnvelopeError with a code.

type EnvelopeEvent

type EnvelopeEvent struct {
	Event EventType
	Topic TopicType
	Hash  common.Hash
	Batch common.Hash
	Peer  enode.ID
	Data  interface{}
}

EnvelopeEvent used for envelopes events.

func CreateMailServerEvent

func CreateMailServerEvent(nodeID enode.ID, payload []byte) (*EnvelopeEvent, error)

CreateMailServerEvent returns EnvelopeEvent with correct data if payload corresponds to any of the know mailserver events: * request completed successfully * request failed If the payload is unknown/unparseable, it returns `nil`

type EventType

type EventType string

EventType used to define known envelope events.

const (
	// EventEnvelopeSent fires when envelope was sent to a peer.
	EventEnvelopeSent EventType = "envelope.sent"
	// EventEnvelopeExpired fires when envelop expired
	EventEnvelopeExpired EventType = "envelope.expired"
	// EventEnvelopeReceived is sent once envelope was received from a peer.
	// EventEnvelopeReceived must be sent to the feed even if envelope was previously in the cache.
	// And event, ideally, should contain information about peer that sent envelope to us.
	EventEnvelopeReceived EventType = "envelope.received"
	// EventBatchAcknowledged is sent when batch of envelopes was acknowledged by a peer.
	EventBatchAcknowledged EventType = "batch.acknowleged"
	// EventEnvelopeAvailable fires when envelop is available for filters
	EventEnvelopeAvailable EventType = "envelope.available"
	// EventMailServerRequestSent fires when such request is sent.
	EventMailServerRequestSent EventType = "mailserver.request.sent"
	// EventMailServerRequestCompleted fires after mailserver sends all the requested messages
	EventMailServerRequestCompleted EventType = "mailserver.request.completed"
	// EventMailServerRequestExpired fires after mailserver the request TTL ends.
	// This event is independent and concurrent to EventMailServerRequestCompleted.
	// Request should be considered as expired only if expiry event was received first.
	EventMailServerRequestExpired EventType = "mailserver.request.expired"
	// EventMailServerEnvelopeArchived fires after an envelope has been archived
	EventMailServerEnvelopeArchived EventType = "mailserver.envelope.archived"
	// EventMailServerSyncFinished fires when the sync of messages is finished.
	EventMailServerSyncFinished EventType = "mailserver.sync.finished"
)

type Filter

type Filter struct {
	Src        *ecdsa.PublicKey  // Sender of the message
	KeyAsym    *ecdsa.PrivateKey // Private Key of recipient
	KeySym     []byte            // Key associated with the Topic
	Topics     [][]byte          // Topics to filter messages with
	PoW        float64           // Proof of work as described in the Whisper spec
	AllowP2P   bool              // Indicates whether this filter is interested in direct peer-to-peer messages
	SymKeyHash common.Hash       // The Keccak256Hash of the symmetric key, needed for optimization

	Messages MessageStore
	// contains filtered or unexported fields
}

Filter represents a Whisper message filter

func (*Filter) MatchEnvelope

func (f *Filter) MatchEnvelope(envelope *Envelope) bool

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. Topics are not checked here, since this is done by topic matchers.

func (*Filter) MatchMessage

func (f *Filter) MatchMessage(msg *ReceivedMessage) bool

MatchMessage checks if the filter matches an already decrypted message (i.e. a Message that has already been handled by MatchEnvelope when checked by a previous filter). Topics are not checked here, since this is done by topic matchers.

func (*Filter) Retrieve

func (f *Filter) Retrieve() []*ReceivedMessage

Retrieve will return the list of all received messages associated to a filter.

func (*Filter) Trigger

func (f *Filter) Trigger(msg *ReceivedMessage)

Trigger adds a yet-unknown message to the filter's list of received messages.

type Filters

type Filters struct {
	// contains filtered or unexported fields
}

Filters represents a collection of filters

func NewFilters

func NewFilters(w *Whisper) *Filters

NewFilters returns a newly created filter collection

func (*Filters) Get

func (fs *Filters) Get(id string) *Filter

Get returns a filter from the collection with a specific ID

func (*Filters) Install

func (fs *Filters) Install(watcher *Filter) (string, error)

Install will add a new filter to the filter collection

func (*Filters) NotifyWatchers

func (fs *Filters) NotifyWatchers(env *Envelope, p2pMessage bool)

NotifyWatchers notifies any filter that has declared interest for the envelope's topic.

func (*Filters) Uninstall

func (fs *Filters) Uninstall(id string) bool

Uninstall will remove a filter whose id has been specified from the filter collection

type Info

type Info struct {
	Memory         int     `json:"memory"`         // Memory size of the floating messages in bytes.
	Messages       int     `json:"messages"`       // Number of floating messages.
	MinPow         float64 `json:"minPow"`         // Minimal accepted PoW
	MaxMessageSize uint32  `json:"maxMessageSize"` // Maximum accepted message size
}

Info contains diagnostic information.

type MailServer

type MailServer interface {
	Archive(env *Envelope)
	DeliverMail(peerID []byte, req *Envelope) // DEPRECATED; user Deliver instead
	Deliver(peerID []byte, req MessagesRequest)
	SyncMail(peerID []byte, req SyncMailRequest) error
}

MailServer represents a mail server, capable of archiving the old messages for subsequent delivery to the peers. Any implementation must ensure that both functions are thread-safe. Also, they must return ASAP. DeliverMail should use directMessagesCode for delivery, in order to bypass the expiry checks.

type MailServerResponse

type MailServerResponse struct {
	LastEnvelopeHash common.Hash
	Cursor           []byte
	Error            error
}

MailServerResponse is the response payload sent by the mailserver

type MemoryMessageStore

type MemoryMessageStore struct {
	// contains filtered or unexported fields
}

MemoryMessageStore stores massages in memory hash table.

func NewMemoryMessageStore

func NewMemoryMessageStore() *MemoryMessageStore

NewMemoryMessageStore returns pointer to an instance of the MemoryMessageStore.

func (*MemoryMessageStore) Add

func (store *MemoryMessageStore) Add(msg *ReceivedMessage) error

Add adds message to store.

func (*MemoryMessageStore) Pop

func (store *MemoryMessageStore) Pop() ([]*ReceivedMessage, error)

Pop returns all available messages and cleans the store.

type Message

type Message struct {
	Sig       []byte    `json:"sig,omitempty"`
	TTL       uint32    `json:"ttl"`
	Timestamp uint32    `json:"timestamp"`
	Topic     TopicType `json:"topic"`
	Payload   []byte    `json:"payload"`
	Padding   []byte    `json:"padding"`
	PoW       float64   `json:"pow"`
	Hash      []byte    `json:"hash"`
	Dst       []byte    `json:"recipientPublicKey,omitempty"`
	P2P       bool      `json:"bool,omitempty"`
}

Message is the RPC representation of a whisper message.

func ToWhisperMessage

func ToWhisperMessage(message *ReceivedMessage) *Message

ToWhisperMessage converts an internal message into an API version.

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

MarshalJSON marshals type Message to a json string

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(input []byte) error

UnmarshalJSON unmarshals type Message to a json string

type MessageParams

type MessageParams struct {
	TTL      uint32
	Src      *ecdsa.PrivateKey
	Dst      *ecdsa.PublicKey
	KeySym   []byte
	Topic    TopicType
	WorkTime uint32
	PoW      float64
	Payload  []byte
	Padding  []byte
}

MessageParams specifies the exact way a message should be wrapped into an Envelope.

type MessageStore

type MessageStore interface {
	Add(*ReceivedMessage) error
	Pop() ([]*ReceivedMessage, error)
}

MessageStore defines interface for temporary message store.

type MessagesRequest

type MessagesRequest struct {
	// ID of the request. The current implementation requires ID to be 32-byte array,
	// however, it's not enforced for future implementation.
	ID []byte `json:"id"`

	// From is a lower bound of time range.
	From uint32 `json:"from"`

	// To is a upper bound of time range.
	To uint32 `json:"to"`

	// Limit determines the number of messages sent by the mail server
	// for the current paginated request.
	Limit uint32 `json:"limit"`

	// Cursor is used as starting point for paginated requests.
	Cursor []byte `json:"cursor"`

	// Bloom is a filter to match requested messages.
	Bloom []byte `json:"bloom"`
}

MessagesRequest contains details of a request of historic messages.

func (MessagesRequest) Validate

func (r MessagesRequest) Validate() error

type MessagesResponse

type MessagesResponse struct {
	// Hash is a hash of all envelopes sent in the single batch.
	Hash common.Hash
	// Per envelope error.
	Errors []EnvelopeError
}

MessagesResponse sent as a response after processing batch of envelopes.

type MetricsRateLimiterHandler

type MetricsRateLimiterHandler struct{}

func (MetricsRateLimiterHandler) ExceedIPLimit

func (MetricsRateLimiterHandler) ExceedIPLimit() error

func (MetricsRateLimiterHandler) ExceedPeerLimit

func (MetricsRateLimiterHandler) ExceedPeerLimit() error

type MultiVersionResponse

type MultiVersionResponse struct {
	Version  uint
	Response rlp.RawValue
}

MultiVersionResponse allows to decode response into chosen version.

func (MultiVersionResponse) DecodeResponse1

func (m MultiVersionResponse) DecodeResponse1() (resp MessagesResponse, err error)

DecodeResponse1 decodes response into first version of the messages response.

type NewMessage

type NewMessage struct {
	SymKeyID   string    `json:"symKeyID"`
	PublicKey  []byte    `json:"pubKey"`
	Sig        string    `json:"sig"`
	TTL        uint32    `json:"ttl"`
	Topic      TopicType `json:"topic"`
	Payload    []byte    `json:"payload"`
	Padding    []byte    `json:"padding"`
	PowTime    uint32    `json:"powTime"`
	PowTarget  float64   `json:"powTarget"`
	TargetPeer string    `json:"targetPeer"`
}

NewMessage represents a new whisper message that is posted through the RPC.

func (NewMessage) MarshalJSON

func (n NewMessage) MarshalJSON() ([]byte, error)

MarshalJSON marshals type NewMessage to a json string

func (*NewMessage) UnmarshalJSON

func (n *NewMessage) UnmarshalJSON(input []byte) error

UnmarshalJSON unmarshals type NewMessage to a json string

type Peer

type Peer struct {
	// contains filtered or unexported fields
}

Peer represents a whisper protocol peer connection.

func (*Peer) ID

func (peer *Peer) ID() []byte

ID returns a peer's id

type PeerRateLimiter

type PeerRateLimiter struct {
	// contains filtered or unexported fields
}

func NewPeerRateLimiter

func NewPeerRateLimiter(cfg *PeerRateLimiterConfig, handlers ...RateLimiterHandler) *PeerRateLimiter

type PeerRateLimiterConfig

type PeerRateLimiterConfig struct {
	LimitPerSecIP      int64
	LimitPerSecPeerID  int64
	WhitelistedIPs     []string
	WhitelistedPeerIDs []enode.ID
}

type PublicWhisperAPI

type PublicWhisperAPI struct {
	// contains filtered or unexported fields
}

PublicWhisperAPI provides the whisper RPC service that can be use publicly without security implications.

func NewPublicWhisperAPI

func NewPublicWhisperAPI(w *Whisper) *PublicWhisperAPI

NewPublicWhisperAPI create a new RPC whisper service.

func (*PublicWhisperAPI) AddPrivateKey

func (api *PublicWhisperAPI) AddPrivateKey(ctx context.Context, privateKey hexutil.Bytes) (string, error)

AddPrivateKey imports the given private key.

func (*PublicWhisperAPI) AddSymKey

func (api *PublicWhisperAPI) AddSymKey(ctx context.Context, key hexutil.Bytes) (string, error)

AddSymKey import a symmetric key. It returns an ID that can be used to refer to the key. Can be used encrypting and decrypting messages where the key is known to both parties.

func (*PublicWhisperAPI) CancelLightClient

func (api *PublicWhisperAPI) CancelLightClient(ctx context.Context) bool

CancelLightClient cancels light client mode.

func (*PublicWhisperAPI) DeleteKeyPair

func (api *PublicWhisperAPI) DeleteKeyPair(ctx context.Context, key string) (bool, error)

DeleteKeyPair removes the key with the given key if it exists.

func (*PublicWhisperAPI) DeleteMessageFilter

func (api *PublicWhisperAPI) DeleteMessageFilter(id string) (bool, error)

DeleteMessageFilter deletes a filter.

func (*PublicWhisperAPI) DeleteSymKey

func (api *PublicWhisperAPI) DeleteSymKey(ctx context.Context, id string) bool

DeleteSymKey deletes the symmetric key that is associated with the given id.

func (*PublicWhisperAPI) GenerateSymKeyFromPassword

func (api *PublicWhisperAPI) GenerateSymKeyFromPassword(ctx context.Context, passwd string) (string, error)

GenerateSymKeyFromPassword derive a key from the given password, stores it, and returns its ID.

func (*PublicWhisperAPI) GetFilterMessages

func (api *PublicWhisperAPI) GetFilterMessages(id string) ([]*Message, error)

GetFilterMessages returns the messages that match the filter criteria and are received between the last poll and now.

func (*PublicWhisperAPI) GetPrivateKey

func (api *PublicWhisperAPI) GetPrivateKey(ctx context.Context, id string) (hexutil.Bytes, error)

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 (*PublicWhisperAPI) GetPublicKey

func (api *PublicWhisperAPI) GetPublicKey(ctx context.Context, id string) (hexutil.Bytes, error)

GetPublicKey returns the public 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 (*PublicWhisperAPI) GetSymKey

func (api *PublicWhisperAPI) GetSymKey(ctx context.Context, id string) (hexutil.Bytes, error)

GetSymKey returns the symmetric key associated with the given id.

func (*PublicWhisperAPI) HasKeyPair

func (api *PublicWhisperAPI) HasKeyPair(ctx context.Context, id string) bool

HasKeyPair returns an indication if the node has a key pair that is associated with the given id.

func (*PublicWhisperAPI) HasSymKey

func (api *PublicWhisperAPI) HasSymKey(ctx context.Context, id string) bool

HasSymKey returns an indication if the node has a symmetric key associated with the given key.

func (*PublicWhisperAPI) Info

func (api *PublicWhisperAPI) Info(ctx context.Context) Info

Info returns diagnostic information about the whisper node.

func (*PublicWhisperAPI) MakeLightClient

func (api *PublicWhisperAPI) MakeLightClient(ctx context.Context) bool

MakeLightClient turns the node into light client, which does not forward any incoming messages, and sends only messages originated in this node.

func (*PublicWhisperAPI) MarkTrustedPeer

func (api *PublicWhisperAPI) MarkTrustedPeer(ctx context.Context, url string) (bool, error)

MarkTrustedPeer marks a 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.

func (*PublicWhisperAPI) Messages

func (api *PublicWhisperAPI) Messages(ctx context.Context, crit Criteria) (*rpc.Subscription, error)

Messages set up a subscription that fires events when messages arrive that match the given set of criteria.

func (*PublicWhisperAPI) NewKeyPair

func (api *PublicWhisperAPI) NewKeyPair(ctx context.Context) (string, error)

NewKeyPair generates a new public and private key pair for message decryption and encryption. It returns an ID that can be used to refer to the keypair.

func (*PublicWhisperAPI) NewMessageFilter

func (api *PublicWhisperAPI) NewMessageFilter(req Criteria) (string, error)

NewMessageFilter creates a new filter that can be used to poll for (new) messages that satisfy the given criteria.

func (*PublicWhisperAPI) NewSymKey

func (api *PublicWhisperAPI) NewSymKey(ctx context.Context) (string, error)

NewSymKey generate a random symmetric key. It returns an ID that can be used to refer to the key. Can be used encrypting and decrypting messages where the key is known to both parties.

func (*PublicWhisperAPI) Post

func (api *PublicWhisperAPI) Post(ctx context.Context, req NewMessage) (hexutil.Bytes, error)

Post posts a message on the Whisper network. returns the hash of the message in case of success.

func (*PublicWhisperAPI) SetBloomFilter

func (api *PublicWhisperAPI) SetBloomFilter(ctx context.Context, bloom hexutil.Bytes) (bool, error)

SetBloomFilter sets the new value of bloom filter, and notifies the peers.

func (*PublicWhisperAPI) SetMaxMessageSize

func (api *PublicWhisperAPI) SetMaxMessageSize(ctx context.Context, size uint32) (bool, error)

SetMaxMessageSize sets the maximum message size that is accepted. Upper limit is defined by MaxMessageSize.

func (*PublicWhisperAPI) SetMinPoW

func (api *PublicWhisperAPI) SetMinPoW(ctx context.Context, pow float64) (bool, error)

SetMinPoW sets the minimum PoW, and notifies the peers.

func (*PublicWhisperAPI) UninstallFilter

func (api *PublicWhisperAPI) UninstallFilter(id string)

UninstallFilter is alias for Unsubscribe

func (*PublicWhisperAPI) Unsubscribe

func (api *PublicWhisperAPI) Unsubscribe(id string)

Unsubscribe disables and removes an existing filter.

func (*PublicWhisperAPI) Version

func (api *PublicWhisperAPI) Version(ctx context.Context) string

Version returns the Whisper sub-protocol version.

type RateLimiterHandler

type RateLimiterHandler interface {
	ExceedPeerLimit() error
	ExceedIPLimit() error
}

type RateLimits

type RateLimits struct {
	IPLimits     uint64 // messages per second from a single IP (default 0, no limits)
	PeerIDLimits uint64 // messages per second from a single peer ID (default 0, no limits)
	TopicLimits  uint64 // messages per second from a single topic (default 0, no limits)
}

RateLimits contains information about rate limit settings. It is exchanged using rateLimitingCode packet or in the handshake.

func (RateLimits) IsZero

func (r RateLimits) IsZero() bool

type RawSyncResponse

type RawSyncResponse struct {
	Envelopes []rlp.RawValue
	Cursor    []byte
	Final     bool // if true it means all envelopes were processed
	Error     string
}

RawSyncResponse is a struct representing a response sent to the peer asking for syncing archived envelopes.

type ReceivedMessage

type ReceivedMessage struct {
	Raw []byte

	Payload   []byte
	Padding   []byte
	Signature []byte
	Salt      []byte

	PoW   float64          // Proof of work as described in the Whisper spec
	Sent  uint32           // Time when the message was posted into the network
	TTL   uint32           // Maximum time to live allowed for the message
	Src   *ecdsa.PublicKey // Message recipient (identity used to decode the message)
	Dst   *ecdsa.PublicKey // Message recipient (identity used to decode the message)
	Topic TopicType

	SymKeyHash   common.Hash // The Keccak256Hash of the key
	EnvelopeHash common.Hash // Message envelope hash to act as a unique id

	P2P bool // is set to true if this message was received from mail server.
}

ReceivedMessage represents a data packet to be received through the Whisper protocol and successfully decrypted.

func (*ReceivedMessage) SigToPubKey

func (msg *ReceivedMessage) SigToPubKey() *ecdsa.PublicKey

SigToPubKey returns the public key associated to the message's signature.

func (*ReceivedMessage) ValidateAndParse

func (msg *ReceivedMessage) ValidateAndParse() bool

ValidateAndParse checks the message validity and extracts the fields in case of success.

type Statistics

type Statistics struct {
	// contains filtered or unexported fields
}

Statistics holds several message-related counter for analytics purposes.

type SyncEventResponse

type SyncEventResponse struct {
	Cursor []byte
	Error  string
}

SyncEventResponse is a response from the Mail Server form which the peer received envelopes.

type SyncMailRequest

type SyncMailRequest struct {
	// Lower is a lower bound of time range for which messages are requested.
	Lower uint32
	// Upper is a lower bound of time range for which messages are requested.
	Upper uint32
	// Bloom is a bloom filter to filter envelopes.
	Bloom []byte
	// Limit is the max number of envelopes to return.
	Limit uint32
	// Cursor is used for pagination of the results.
	Cursor []byte
}

SyncMailRequest contains details which envelopes should be synced between Mail Servers.

func (SyncMailRequest) Validate

func (r SyncMailRequest) Validate() error

Validate checks request's fields if they are valid.

type SyncResponse

type SyncResponse struct {
	Envelopes []*Envelope
	Cursor    []byte
	Final     bool // if true it means all envelopes were processed
	Error     string
}

SyncResponse is a struct representing a response sent to the peer asking for syncing archived envelopes.

type TimeSyncError

type TimeSyncError error

TimeSyncError error for clock skew errors.

type TopicType

type TopicType [TopicLength]byte

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.

func BytesToTopic

func BytesToTopic(b []byte) (t TopicType)

BytesToTopic converts from the byte array representation of a topic into the TopicType type.

func (TopicType) MarshalText

func (t TopicType) MarshalText() ([]byte, error)

MarshalText returns the hex representation of t.

func (*TopicType) String

func (t *TopicType) String() string

String converts a topic byte array to a string representation.

func (*TopicType) UnmarshalText

func (t *TopicType) UnmarshalText(input []byte) error

UnmarshalText parses a hex representation to a topic.

type Version1MessageResponse

type Version1MessageResponse struct {
	Version  uint
	Response MessagesResponse
}

Version1MessageResponse first version of the message response.

func NewMessagesResponse

func NewMessagesResponse(batch common.Hash, errors []EnvelopeError) Version1MessageResponse

NewMessagesResponse returns instane of the version messages response.

type Whisper

type Whisper struct {
	// contains filtered or unexported fields
}

Whisper represents a dark communication interface through the Ethereum network, using its very own P2P communication layer.

func New

func New(cfg *Config) *Whisper

New creates a Whisper client ready to communicate through the Ethereum P2P network.

func (*Whisper) APIs

func (whisper *Whisper) APIs() []rpc.API

APIs returns the RPC descriptors the Whisper implementation offers

func (*Whisper) AddKeyPair

func (whisper *Whisper) AddKeyPair(key *ecdsa.PrivateKey) (string, error)

AddKeyPair imports a asymmetric private key and returns it identifier.

func (*Whisper) AddSymKey

func (whisper *Whisper) AddSymKey(id string, key []byte) (string, error)

AddSymKey stores the key with a given id.

func (*Whisper) AddSymKeyDirect

func (whisper *Whisper) AddSymKeyDirect(key []byte) (string, error)

AddSymKeyDirect stores the key, and returns its id.

func (*Whisper) AddSymKeyFromPassword

func (whisper *Whisper) AddSymKeyFromPassword(password string) (string, error)

AddSymKeyFromPassword generates the key from password, stores it, and returns its id.

func (*Whisper) AllowP2PMessagesFromPeer

func (whisper *Whisper) AllowP2PMessagesFromPeer(peerID []byte) error

AllowP2PMessagesFromPeer marks specific peer trusted, which will allow it to send historic (expired) messages.

func (*Whisper) BloomFilter

func (whisper *Whisper) BloomFilter() []byte

BloomFilter returns the aggregated bloom filter for all the topics of interest. The nodes are required to send only messages that match the advertised bloom filter. If a message does not match the bloom, it will tantamount to spam, and the peer will be disconnected.

func (*Whisper) BloomFilterTolerance

func (whisper *Whisper) BloomFilterTolerance() []byte

BloomFilterTolerance returns the bloom filter which is tolerated for a limited time after new bloom was advertised to the peers. If sufficient time have elapsed or no change of bloom filter have ever occurred, the return value will be the same as return value of BloomFilter().

func (*Whisper) DeleteKeyPair

func (whisper *Whisper) DeleteKeyPair(key string) bool

DeleteKeyPair deletes the key with the specified ID if it exists.

func (*Whisper) DeleteKeyPairs

func (whisper *Whisper) DeleteKeyPairs() error

DeleteKeyPairs removes all cryptographic identities known to the node

func (*Whisper) DeleteSymKey

func (whisper *Whisper) DeleteSymKey(id string) bool

DeleteSymKey deletes the key associated with the name string if it exists.

func (*Whisper) Envelopes

func (whisper *Whisper) Envelopes() []*Envelope

Envelopes retrieves all the messages currently pooled by the node.

func (*Whisper) GenerateSymKey

func (whisper *Whisper) GenerateSymKey() (string, error)

GenerateSymKey generates a random symmetric key and stores it under id, which is then returned. Will be used in the future for session key exchange.

func (*Whisper) GetCurrentTime

func (whisper *Whisper) GetCurrentTime() time.Time

GetCurrentTime returns current time.

func (*Whisper) GetEnvelope

func (w *Whisper) GetEnvelope(hash common.Hash) *Envelope

GetEnvelope retrieves an envelope from the message queue by its hash. It returns nil if the envelope can not be found.

func (*Whisper) GetFilter

func (whisper *Whisper) GetFilter(id string) *Filter

GetFilter returns the filter by id.

func (*Whisper) GetPrivateKey

func (whisper *Whisper) GetPrivateKey(id string) (*ecdsa.PrivateKey, error)

GetPrivateKey retrieves the private key of the specified identity.

func (*Whisper) GetSymKey

func (whisper *Whisper) GetSymKey(id string) ([]byte, error)

GetSymKey returns the symmetric key associated with the given id.

func (*Whisper) HandlePeer

func (whisper *Whisper) HandlePeer(peer *p2p.Peer, rw p2p.MsgReadWriter) error

HandlePeer is called by the underlying P2P layer when the whisper sub-protocol connection is negotiated.

func (*Whisper) HasKeyPair

func (whisper *Whisper) HasKeyPair(id string) bool

HasKeyPair checks if the whisper node is configured with the private key of the specified public pair.

func (*Whisper) HasSymKey

func (whisper *Whisper) HasSymKey(id string) bool

HasSymKey returns true if there is a key associated with the given id. Otherwise returns false.

func (*Whisper) LightClientMode

func (whisper *Whisper) LightClientMode() bool

LightClientMode indicates is this node is light client (does not forward any messages)

func (*Whisper) LightClientModeConnectionRestricted

func (whisper *Whisper) LightClientModeConnectionRestricted() bool

LightClientModeConnectionRestricted indicates that connection to light client in light client mode not allowed

func (*Whisper) MaxMessageSize

func (whisper *Whisper) MaxMessageSize() uint32

MaxMessageSize returns the maximum accepted message size.

func (*Whisper) MinPow

func (whisper *Whisper) MinPow() float64

MinPow returns the PoW value required by this node.

func (*Whisper) MinPowTolerance

func (whisper *Whisper) MinPowTolerance() float64

MinPowTolerance returns the value of minimum PoW which is tolerated for a limited time after PoW was changed. If sufficient time have elapsed or no change of PoW have ever occurred, the return value will be the same as return value of MinPow().

func (*Whisper) NewKeyPair

func (whisper *Whisper) NewKeyPair() (string, error)

NewKeyPair generates a new cryptographic identity for the client, and injects it into the known identities for message decryption. Returns ID of the new key pair.

func (*Whisper) NewMessageStore

func (whisper *Whisper) NewMessageStore() MessageStore

NewMessageStore returns object that implements MessageStore.

func (*Whisper) Overflow

func (whisper *Whisper) Overflow() bool

Overflow returns an indication if the message queue is full.

func (*Whisper) Protocols

func (whisper *Whisper) Protocols() []p2p.Protocol

Protocols returns the whisper sub-protocols ran by this particular client.

func (*Whisper) RateLimits

func (whisper *Whisper) RateLimits() RateLimits

RateLimiting returns RateLimits information.

func (*Whisper) RegisterBridge

func (whisper *Whisper) RegisterBridge(b Bridge)

RegisterBridge registers a new Bridge that moves envelopes between different subprotocols. It's important that a bridge is registered before the service is started, otherwise, it won't read and propagate envelopes.

func (*Whisper) RegisterMailServer

func (whisper *Whisper) RegisterMailServer(server MailServer)

RegisterServer registers MailServer interface. MailServer will process all the incoming messages with p2pRequestCode.

func (*Whisper) RequestHistoricMessages

func (whisper *Whisper) RequestHistoricMessages(peerID []byte, envelope *Envelope) error

RequestHistoricMessages sends a message with p2pRequestCode to a specific peer, which is known to implement MailServer interface, and is supposed to process this request and respond with a number of peer-to-peer messages (possibly expired), which are not supposed to be forwarded any further. The whisper protocol is agnostic of the format and contents of envelope.

func (*Whisper) RequestHistoricMessagesWithTimeout

func (whisper *Whisper) RequestHistoricMessagesWithTimeout(peerID []byte, envelope *Envelope, timeout time.Duration) error

func (*Whisper) Send

func (whisper *Whisper) Send(envelope *Envelope) error

Send injects a message into the whisper send queue, to be distributed in the network in the coming cycles.

func (*Whisper) SendHistoricMessageResponse

func (whisper *Whisper) SendHistoricMessageResponse(peerID []byte, payload []byte) error

func (*Whisper) SendMessagesRequest

func (whisper *Whisper) SendMessagesRequest(peerID []byte, request MessagesRequest) error

func (*Whisper) SendP2PDirect

func (whisper *Whisper) SendP2PDirect(peerID []byte, envelopes ...*Envelope) error

SendP2PDirect sends a peer-to-peer message to a specific peer. If only a single envelope is given, data is sent as a single object rather than a slice. This is important to keep this method backward compatible as it used to send only single envelopes.

func (*Whisper) SendP2PMessage

func (whisper *Whisper) SendP2PMessage(peerID []byte, envelopes ...*Envelope) error

SendP2PMessage sends a peer-to-peer message to a specific peer.

func (*Whisper) SendRawP2PDirect

func (whisper *Whisper) SendRawP2PDirect(peerID []byte, envelopes ...rlp.RawValue) error

SendRawP2PDirect sends a peer-to-peer message to a specific peer. If only a single envelope is given, data is sent as a single object rather than a slice. This is important to keep this method backward compatible as it used to send only single envelopes.

func (*Whisper) SendRawSyncResponse

func (whisper *Whisper) SendRawSyncResponse(peerID []byte, data RawSyncResponse) error

SendRawSyncResponse sends a response to a Mail Server with a slice of envelopes.

func (*Whisper) SendSyncResponse

func (whisper *Whisper) SendSyncResponse(peerID []byte, data SyncResponse) error

SendSyncResponse sends a response to a Mail Server with a slice of envelopes.

func (*Whisper) SetBloomFilter

func (whisper *Whisper) SetBloomFilter(bloom []byte) error

SetBloomFilter sets the new bloom filter

func (*Whisper) SetLightClientMode

func (whisper *Whisper) SetLightClientMode(v bool)

SetLightClientMode makes node light client (does not forward any messages)

func (*Whisper) SetMaxMessageSize

func (whisper *Whisper) SetMaxMessageSize(size uint32) error

SetMaxMessageSize sets the maximal message size allowed by this node

func (*Whisper) SetMessageStore

func (whisper *Whisper) SetMessageStore(fabric func() MessageStore)

SetMessageStore allows to inject custom implementation of the message store.

func (*Whisper) SetMinimumPoW

func (whisper *Whisper) SetMinimumPoW(val float64) error

SetMinimumPoW sets the minimal PoW required by this node

func (*Whisper) SetMinimumPowTest

func (whisper *Whisper) SetMinimumPowTest(val float64)

SetMinimumPowTest sets the minimal PoW in test environment

func (*Whisper) SetRateLimiter

func (whisper *Whisper) SetRateLimiter(r *PeerRateLimiter)

SetRateLimiter sets an active rate limiter. It must be run before Whisper is started.

func (*Whisper) SetTimeSource

func (whisper *Whisper) SetTimeSource(timesource func() time.Time)

SetTimeSource assigns a particular source of time to a whisper object.

func (*Whisper) Start

func (whisper *Whisper) Start(*p2p.Server) error

Start implements node.Service, starting the background data propagation thread of the Whisper protocol.

func (*Whisper) Stats

func (whisper *Whisper) Stats() Statistics

Stats returns the whisper node statistics.

func (*Whisper) Stop

func (whisper *Whisper) Stop() error

Stop implements node.Service, stopping the background data propagation thread of the Whisper protocol.

func (*Whisper) Subscribe

func (whisper *Whisper) Subscribe(f *Filter) (string, error)

Subscribe installs a new message handler used for filtering, decrypting and subsequent storing of incoming messages.

func (*Whisper) SubscribeEnvelopeEvents

func (whisper *Whisper) SubscribeEnvelopeEvents(events chan<- EnvelopeEvent) event.Subscription

SubscribeEnvelopeEvents subscribes to envelopes feed. In order to prevent blocking whisper producers events must be amply buffered.

func (*Whisper) SyncMessages

func (whisper *Whisper) SyncMessages(peerID []byte, req SyncMailRequest) error

SyncMessages can be sent between two Mail Servers and syncs envelopes between them.

func (*Whisper) Unsubscribe

func (whisper *Whisper) Unsubscribe(id string) error

Unsubscribe removes an installed message handler.

func (*Whisper) UnsubscribeMany

func (whisper *Whisper) UnsubscribeMany(ids []string) error

UnsubscribeMany removes an installed message handler.

func (*Whisper) Version

func (whisper *Whisper) Version() uint

Version returns the whisper sub-protocols version number.

Directories

Path Synopsis
module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL