aboutsummaryrefslogtreecommitdiffstats
path: root/swarm/pss
diff options
context:
space:
mode:
Diffstat (limited to 'swarm/pss')
-rw-r--r--swarm/pss/handshake.go2
-rw-r--r--swarm/pss/notify/notify.go394
-rw-r--r--swarm/pss/notify/notify_test.go252
-rw-r--r--swarm/pss/protocol.go8
-rw-r--r--swarm/pss/pss.go10
-rw-r--r--swarm/pss/pss_test.go8
6 files changed, 664 insertions, 10 deletions
diff --git a/swarm/pss/handshake.go b/swarm/pss/handshake.go
index 3b44847ec..e3ead77d0 100644
--- a/swarm/pss/handshake.go
+++ b/swarm/pss/handshake.go
@@ -385,7 +385,7 @@ func (ctl *HandshakeController) sendKey(pubkeyid string, topic *Topic, keycount
// generate new keys to send
for i := 0; i < len(recvkeyids); i++ {
var err error
- recvkeyids[i], err = ctl.pss.generateSymmetricKey(*topic, to, true)
+ recvkeyids[i], err = ctl.pss.GenerateSymmetricKey(*topic, to, true)
if err != nil {
return []string{}, fmt.Errorf("set receive symkey fail (pubkey %x topic %x): %v", pubkeyid, topic, err)
}
diff --git a/swarm/pss/notify/notify.go b/swarm/pss/notify/notify.go
new file mode 100644
index 000000000..723092c32
--- /dev/null
+++ b/swarm/pss/notify/notify.go
@@ -0,0 +1,394 @@
+package notify
+
+import (
+ "crypto/ecdsa"
+ "fmt"
+ "sync"
+
+ "github.com/ethereum/go-ethereum/common/hexutil"
+ "github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/p2p"
+ "github.com/ethereum/go-ethereum/rlp"
+ "github.com/ethereum/go-ethereum/swarm/log"
+ "github.com/ethereum/go-ethereum/swarm/pss"
+)
+
+const (
+ // sent from requester to updater to request start of notifications
+ MsgCodeStart = iota
+
+ // sent from updater to requester, contains a notification plus a new symkey to replace the old
+ MsgCodeNotifyWithKey
+
+ // sent from updater to requester, contains a notification
+ MsgCodeNotify
+
+ // sent from requester to updater to request stop of notifications (currently unused)
+ MsgCodeStop
+ MsgCodeMax
+)
+
+const (
+ DefaultAddressLength = 1
+ symKeyLength = 32 // this should be gotten from source
+)
+
+var (
+ // control topic is used before symmetric key issuance completes
+ controlTopic = pss.Topic{0x00, 0x00, 0x00, 0x01}
+)
+
+// when code is MsgCodeStart, Payload is address
+// when code is MsgCodeNotifyWithKey, Payload is notification | symkey
+// when code is MsgCodeNotify, Payload is notification
+// when code is MsgCodeStop, Payload is address
+type Msg struct {
+ Code byte
+ Name []byte
+ Payload []byte
+ namestring string
+}
+
+// NewMsg creates a new notification message object
+func NewMsg(code byte, name string, payload []byte) *Msg {
+ return &Msg{
+ Code: code,
+ Name: []byte(name),
+ Payload: payload,
+ namestring: name,
+ }
+}
+
+// NewMsgFromPayload decodes a serialized message payload into a new notification message object
+func NewMsgFromPayload(payload []byte) (*Msg, error) {
+ msg := &Msg{}
+ err := rlp.DecodeBytes(payload, msg)
+ if err != nil {
+ return nil, err
+ }
+ msg.namestring = string(msg.Name)
+ return msg, nil
+}
+
+// a notifier has one sendBin entry for each address space it sends messages to
+type sendBin struct {
+ address pss.PssAddress
+ symKeyId string
+ count int
+}
+
+// represents a single notification service
+// only subscription address bins that match the address of a notification client have entries.
+type notifier struct {
+ bins map[string]*sendBin
+ topic pss.Topic // identifies the resource for pss receiver
+ threshold int // amount of address bytes used in bins
+ updateC <-chan []byte
+ quitC chan struct{}
+}
+
+func (n *notifier) removeSubscription() {
+ n.quitC <- struct{}{}
+}
+
+// represents an individual subscription made by a public key at a specific address/neighborhood
+type subscription struct {
+ pubkeyId string
+ address pss.PssAddress
+ handler func(string, []byte) error
+}
+
+// Controller is the interface to control, add and remove notification services and subscriptions
+type Controller struct {
+ pss *pss.Pss
+ notifiers map[string]*notifier
+ subscriptions map[string]*subscription
+ mu sync.Mutex
+}
+
+// NewController creates a new Controller object
+func NewController(ps *pss.Pss) *Controller {
+ ctrl := &Controller{
+ pss: ps,
+ notifiers: make(map[string]*notifier),
+ subscriptions: make(map[string]*subscription),
+ }
+ ctrl.pss.Register(&controlTopic, ctrl.Handler)
+ return ctrl
+}
+
+// IsActive is used to check if a notification service exists for a specified id string
+// Returns true if exists, false if not
+func (c *Controller) IsActive(name string) bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.isActive(name)
+}
+
+func (c *Controller) isActive(name string) bool {
+ _, ok := c.notifiers[name]
+ return ok
+}
+
+// Subscribe is used by a client to request notifications from a notification service provider
+// It will create a MsgCodeStart message and send asymmetrically to the provider using its public key and routing address
+// The handler function is a callback that will be called when notifications are received
+// Fails if the request pss cannot be sent or if the update message could not be serialized
+func (c *Controller) Subscribe(name string, pubkey *ecdsa.PublicKey, address pss.PssAddress, handler func(string, []byte) error) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ msg := NewMsg(MsgCodeStart, name, c.pss.BaseAddr())
+ c.pss.SetPeerPublicKey(pubkey, controlTopic, &address)
+ pubkeyId := hexutil.Encode(crypto.FromECDSAPub(pubkey))
+ smsg, err := rlp.EncodeToBytes(msg)
+ if err != nil {
+ return err
+ }
+ err = c.pss.SendAsym(pubkeyId, controlTopic, smsg)
+ if err != nil {
+ return err
+ }
+ c.subscriptions[name] = &subscription{
+ pubkeyId: pubkeyId,
+ address: address,
+ handler: handler,
+ }
+ return nil
+}
+
+// Unsubscribe, perhaps unsurprisingly, undoes the effects of Subscribe
+// Fails if the subscription does not exist, if the request pss cannot be sent or if the update message could not be serialized
+func (c *Controller) Unsubscribe(name string) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ sub, ok := c.subscriptions[name]
+ if !ok {
+ return fmt.Errorf("Unknown subscription '%s'", name)
+ }
+ msg := NewMsg(MsgCodeStop, name, sub.address)
+ smsg, err := rlp.EncodeToBytes(msg)
+ if err != nil {
+ return err
+ }
+ err = c.pss.SendAsym(sub.pubkeyId, controlTopic, smsg)
+ if err != nil {
+ return err
+ }
+ delete(c.subscriptions, name)
+ return nil
+}
+
+// NewNotifier is used by a notification service provider to create a new notification service
+// It takes a name as identifier for the resource, a threshold indicating the granularity of the subscription address bin
+// It then starts an event loop which listens to the supplied update channel and executes notifications on channel receives
+// Fails if a notifier already is registered on the name
+//func (c *Controller) NewNotifier(name string, threshold int, contentFunc func(string) ([]byte, error)) error {
+func (c *Controller) NewNotifier(name string, threshold int, updateC <-chan []byte) (func(), error) {
+ c.mu.Lock()
+ if c.isActive(name) {
+ c.mu.Unlock()
+ return nil, fmt.Errorf("Notification service %s already exists in controller", name)
+ }
+ quitC := make(chan struct{})
+ c.notifiers[name] = &notifier{
+ bins: make(map[string]*sendBin),
+ topic: pss.BytesToTopic([]byte(name)),
+ threshold: threshold,
+ updateC: updateC,
+ quitC: quitC,
+ //contentFunc: contentFunc,
+ }
+ c.mu.Unlock()
+ go func() {
+ for {
+ select {
+ case <-quitC:
+ return
+ case data := <-updateC:
+ c.notify(name, data)
+ }
+ }
+ }()
+
+ return c.notifiers[name].removeSubscription, nil
+}
+
+// RemoveNotifier is used to stop a notification service.
+// It cancels the event loop listening to the notification provider's update channel
+func (c *Controller) RemoveNotifier(name string) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ currentNotifier, ok := c.notifiers[name]
+ if !ok {
+ return fmt.Errorf("Unknown notification service %s", name)
+ }
+ currentNotifier.removeSubscription()
+ delete(c.notifiers, name)
+ return nil
+}
+
+// Notify is called by a notification service provider to issue a new notification
+// It takes the name of the notification service and the data to be sent.
+// It fails if a notifier with this name does not exist or if data could not be serialized
+// Note that it does NOT fail on failure to send a message
+func (c *Controller) notify(name string, data []byte) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if !c.isActive(name) {
+ return fmt.Errorf("Notification service %s doesn't exist", name)
+ }
+ msg := NewMsg(MsgCodeNotify, name, data)
+ smsg, err := rlp.EncodeToBytes(msg)
+ if err != nil {
+ return err
+ }
+ for _, m := range c.notifiers[name].bins {
+ log.Debug("sending pss notify", "name", name, "addr", fmt.Sprintf("%x", m.address), "topic", fmt.Sprintf("%x", c.notifiers[name].topic), "data", data)
+ go func(m *sendBin) {
+ err = c.pss.SendSym(m.symKeyId, c.notifiers[name].topic, smsg)
+ if err != nil {
+ log.Warn("Failed to send notify to addr %x: %v", m.address, err)
+ }
+ }(m)
+ }
+ return nil
+}
+
+// check if we already have the bin
+// if we do, retrieve the symkey from it and increment the count
+// if we dont make a new symkey and a new bin entry
+func (c *Controller) addToBin(ntfr *notifier, address []byte) (symKeyId string, pssAddress pss.PssAddress, err error) {
+
+ // parse the address from the message and truncate if longer than our bins threshold
+ if len(address) > ntfr.threshold {
+ address = address[:ntfr.threshold]
+ }
+
+ pssAddress = pss.PssAddress(address)
+ hexAddress := fmt.Sprintf("%x", address)
+ currentBin, ok := ntfr.bins[hexAddress]
+ if ok {
+ currentBin.count++
+ symKeyId = currentBin.symKeyId
+ } else {
+ symKeyId, err = c.pss.GenerateSymmetricKey(ntfr.topic, &pssAddress, false)
+ if err != nil {
+ return "", nil, err
+ }
+ ntfr.bins[hexAddress] = &sendBin{
+ address: address,
+ symKeyId: symKeyId,
+ count: 1,
+ }
+ }
+ return symKeyId, pssAddress, nil
+}
+
+func (c *Controller) handleStartMsg(msg *Msg, keyid string) (err error) {
+
+ keyidbytes, err := hexutil.Decode(keyid)
+ if err != nil {
+ return err
+ }
+ pubkey, err := crypto.UnmarshalPubkey(keyidbytes)
+ if err != nil {
+ return err
+ }
+
+ // if name is not registered for notifications we will not react
+ currentNotifier, ok := c.notifiers[msg.namestring]
+ if !ok {
+ return fmt.Errorf("Subscribe attempted on unknown resource '%s'", msg.namestring)
+ }
+
+ // add to or open new bin
+ symKeyId, pssAddress, err := c.addToBin(currentNotifier, msg.Payload)
+ if err != nil {
+ return err
+ }
+
+ // add to address book for send initial notify
+ symkey, err := c.pss.GetSymmetricKey(symKeyId)
+ if err != nil {
+ return err
+ }
+ err = c.pss.SetPeerPublicKey(pubkey, controlTopic, &pssAddress)
+ if err != nil {
+ return err
+ }
+
+ // TODO this is set to zero-length byte pending decision on protocol for initial message, whether it should include message or not, and how to trigger the initial message so that current state of MRU is sent upon subscription
+ notify := []byte{}
+ replyMsg := NewMsg(MsgCodeNotifyWithKey, msg.namestring, make([]byte, len(notify)+symKeyLength))
+ copy(replyMsg.Payload, notify)
+ copy(replyMsg.Payload[len(notify):], symkey)
+ sReplyMsg, err := rlp.EncodeToBytes(replyMsg)
+ if err != nil {
+ return err
+ }
+ return c.pss.SendAsym(keyid, controlTopic, sReplyMsg)
+}
+
+func (c *Controller) handleNotifyWithKeyMsg(msg *Msg) error {
+ symkey := msg.Payload[len(msg.Payload)-symKeyLength:]
+ topic := pss.BytesToTopic(msg.Name)
+
+ // \TODO keep track of and add actual address
+ updaterAddr := pss.PssAddress([]byte{})
+ c.pss.SetSymmetricKey(symkey, topic, &updaterAddr, true)
+ c.pss.Register(&topic, c.Handler)
+ return c.subscriptions[msg.namestring].handler(msg.namestring, msg.Payload[:len(msg.Payload)-symKeyLength])
+}
+
+func (c *Controller) handleStopMsg(msg *Msg) error {
+ // if name is not registered for notifications we will not react
+ currentNotifier, ok := c.notifiers[msg.namestring]
+ if !ok {
+ return fmt.Errorf("Unsubscribe attempted on unknown resource '%s'", msg.namestring)
+ }
+
+ // parse the address from the message and truncate if longer than our bins' address length threshold
+ address := msg.Payload
+ if len(msg.Payload) > currentNotifier.threshold {
+ address = address[:currentNotifier.threshold]
+ }
+
+ // remove the entry from the bin if it exists, and remove the bin if it's the last remaining one
+ hexAddress := fmt.Sprintf("%x", address)
+ currentBin, ok := currentNotifier.bins[hexAddress]
+ if !ok {
+ return fmt.Errorf("found no active bin for address %s", hexAddress)
+ }
+ currentBin.count--
+ if currentBin.count == 0 { // if no more clients in this bin, remove it
+ delete(currentNotifier.bins, hexAddress)
+ }
+ return nil
+}
+
+// Handler is the pss topic handler to be used to process notification service messages
+// It should be registered in the pss of both to any notification service provides and clients using the service
+func (c *Controller) Handler(smsg []byte, p *p2p.Peer, asymmetric bool, keyid string) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ log.Debug("notify controller handler", "keyid", keyid)
+
+ // see if the message is valid
+ msg, err := NewMsgFromPayload(smsg)
+ if err != nil {
+ return err
+ }
+
+ switch msg.Code {
+ case MsgCodeStart:
+ return c.handleStartMsg(msg, keyid)
+ case MsgCodeNotifyWithKey:
+ return c.handleNotifyWithKeyMsg(msg)
+ case MsgCodeNotify:
+ return c.subscriptions[msg.namestring].handler(msg.namestring, msg.Payload)
+ case MsgCodeStop:
+ return c.handleStopMsg(msg)
+ }
+
+ return fmt.Errorf("Invalid message code: %d", msg.Code)
+}
diff --git a/swarm/pss/notify/notify_test.go b/swarm/pss/notify/notify_test.go
new file mode 100644
index 000000000..3c655f215
--- /dev/null
+++ b/swarm/pss/notify/notify_test.go
@@ -0,0 +1,252 @@
+package notify
+
+import (
+ "bytes"
+ "context"
+ "flag"
+ "fmt"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/ethereum/go-ethereum/common/hexutil"
+ "github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/log"
+ "github.com/ethereum/go-ethereum/node"
+ "github.com/ethereum/go-ethereum/p2p/discover"
+ "github.com/ethereum/go-ethereum/p2p/simulations"
+ "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
+ "github.com/ethereum/go-ethereum/swarm/network"
+ "github.com/ethereum/go-ethereum/swarm/pss"
+ "github.com/ethereum/go-ethereum/swarm/state"
+ whisper "github.com/ethereum/go-ethereum/whisper/whisperv5"
+)
+
+var (
+ loglevel = flag.Int("l", 3, "loglevel")
+ psses map[string]*pss.Pss
+ w *whisper.Whisper
+ wapi *whisper.PublicWhisperAPI
+)
+
+func init() {
+ flag.Parse()
+ hs := log.StreamHandler(os.Stderr, log.TerminalFormat(true))
+ hf := log.LvlFilterHandler(log.Lvl(*loglevel), hs)
+ h := log.CallerFileHandler(hf)
+ log.Root().SetHandler(h)
+
+ w = whisper.New(&whisper.DefaultConfig)
+ wapi = whisper.NewPublicWhisperAPI(w)
+ psses = make(map[string]*pss.Pss)
+}
+
+// Creates a client node and notifier node
+// Client sends pss notifications requests
+// notifier sends initial notification with symmetric key, and
+// second notification symmetrically encrypted
+func TestStart(t *testing.T) {
+ adapter := adapters.NewSimAdapter(newServices(false))
+ net := simulations.NewNetwork(adapter, &simulations.NetworkConfig{
+ ID: "0",
+ DefaultService: "bzz",
+ })
+ leftNodeConf := adapters.RandomNodeConfig()
+ leftNodeConf.Services = []string{"bzz", "pss"}
+ leftNode, err := net.NewNodeWithConfig(leftNodeConf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = net.Start(leftNode.ID())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ rightNodeConf := adapters.RandomNodeConfig()
+ rightNodeConf.Services = []string{"bzz", "pss"}
+ rightNode, err := net.NewNodeWithConfig(rightNodeConf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = net.Start(rightNode.ID())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ err = net.Connect(rightNode.ID(), leftNode.ID())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ leftRpc, err := leftNode.Client()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ rightRpc, err := rightNode.Client()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var leftAddr string
+ err = leftRpc.Call(&leftAddr, "pss_baseAddr")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var rightAddr string
+ err = rightRpc.Call(&rightAddr, "pss_baseAddr")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var leftPub string
+ err = leftRpc.Call(&leftPub, "pss_getPublicKey")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var rightPub string
+ err = rightRpc.Call(&rightPub, "pss_getPublicKey")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ rsrcName := "foo.eth"
+ rsrcTopic := pss.BytesToTopic([]byte(rsrcName))
+
+ // wait for kademlia table to populate
+ time.Sleep(time.Second)
+
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
+ defer cancel()
+ rmsgC := make(chan *pss.APIMsg)
+ rightSub, err := rightRpc.Subscribe(ctx, "pss", rmsgC, "receive", controlTopic)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rightSub.Unsubscribe()
+
+ updateC := make(chan []byte)
+ updateMsg := []byte{}
+ ctrlClient := NewController(psses[rightPub])
+ ctrlNotifier := NewController(psses[leftPub])
+ ctrlNotifier.NewNotifier("foo.eth", 2, updateC)
+
+ pubkeybytes, err := hexutil.Decode(leftPub)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pubkey, err := crypto.UnmarshalPubkey(pubkeybytes)
+ if err != nil {
+ t.Fatal(err)
+ }
+ addrbytes, err := hexutil.Decode(leftAddr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctrlClient.Subscribe(rsrcName, pubkey, addrbytes, func(s string, b []byte) error {
+ if s != "foo.eth" || !bytes.Equal(updateMsg, b) {
+ t.Fatalf("unexpected result in client handler: '%s':'%x'", s, b)
+ }
+ log.Info("client handler receive", "s", s, "b", b)
+ return nil
+ })
+
+ var inMsg *pss.APIMsg
+ select {
+ case inMsg = <-rmsgC:
+ case <-ctx.Done():
+ t.Fatal(ctx.Err())
+ }
+
+ dMsg, err := NewMsgFromPayload(inMsg.Msg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if dMsg.namestring != rsrcName {
+ t.Fatalf("expected name '%s', got '%s'", rsrcName, dMsg.namestring)
+ }
+ if !bytes.Equal(dMsg.Payload[:len(updateMsg)], updateMsg) {
+ t.Fatalf("expected payload first %d bytes '%x', got '%x'", len(updateMsg), updateMsg, dMsg.Payload[:len(updateMsg)])
+ }
+ if len(updateMsg)+symKeyLength != len(dMsg.Payload) {
+ t.Fatalf("expected payload length %d, have %d", len(updateMsg)+symKeyLength, len(dMsg.Payload))
+ }
+
+ rightSubUpdate, err := rightRpc.Subscribe(ctx, "pss", rmsgC, "receive", rsrcTopic)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rightSubUpdate.Unsubscribe()
+
+ updateMsg = []byte("plugh")
+ updateC <- updateMsg
+ select {
+ case inMsg = <-rmsgC:
+ case <-ctx.Done():
+ log.Error("timed out waiting for msg", "topic", fmt.Sprintf("%x", rsrcTopic))
+ t.Fatal(ctx.Err())
+ }
+ dMsg, err = NewMsgFromPayload(inMsg.Msg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if dMsg.namestring != rsrcName {
+ t.Fatalf("expected name %s, got %s", rsrcName, dMsg.namestring)
+ }
+ if !bytes.Equal(dMsg.Payload, updateMsg) {
+ t.Fatalf("expected payload '%x', got '%x'", updateMsg, dMsg.Payload)
+ }
+
+}
+
+func newServices(allowRaw bool) adapters.Services {
+ stateStore := state.NewInmemoryStore()
+ kademlias := make(map[discover.NodeID]*network.Kademlia)
+ kademlia := func(id discover.NodeID) *network.Kademlia {
+ if k, ok := kademlias[id]; ok {
+ return k
+ }
+ addr := network.NewAddrFromNodeID(id)
+ params := network.NewKadParams()
+ params.MinProxBinSize = 2
+ params.MaxBinSize = 3
+ params.MinBinSize = 1
+ params.MaxRetries = 1000
+ params.RetryExponent = 2
+ params.RetryInterval = 1000000
+ kademlias[id] = network.NewKademlia(addr.Over(), params)
+ return kademlias[id]
+ }
+ return adapters.Services{
+ "pss": func(ctx *adapters.ServiceContext) (node.Service, error) {
+ ctxlocal, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ keys, err := wapi.NewKeyPair(ctxlocal)
+ privkey, err := w.GetPrivateKey(keys)
+ pssp := pss.NewPssParams().WithPrivateKey(privkey)
+ pssp.MsgTTL = time.Second * 30
+ pssp.AllowRaw = allowRaw
+ pskad := kademlia(ctx.Config.ID)
+ ps, err := pss.NewPss(pskad, pssp)
+ if err != nil {
+ return nil, err
+ }
+ //psses[common.ToHex(crypto.FromECDSAPub(&privkey.PublicKey))] = ps
+ psses[hexutil.Encode(crypto.FromECDSAPub(&privkey.PublicKey))] = ps
+ return ps, nil
+ },
+ "bzz": func(ctx *adapters.ServiceContext) (node.Service, error) {
+ addr := network.NewAddrFromNodeID(ctx.Config.ID)
+ hp := network.NewHiveParams()
+ hp.Discovery = false
+ config := &network.BzzConfig{
+ OverlayAddr: addr.Over(),
+ UnderlayAddr: addr.Under(),
+ HiveParams: hp,
+ }
+ return network.NewBzz(config, kademlia(ctx.Config.ID), stateStore, nil, nil), nil
+ },
+ }
+}
diff --git a/swarm/pss/protocol.go b/swarm/pss/protocol.go
index bf23e49da..5fcae090e 100644
--- a/swarm/pss/protocol.go
+++ b/swarm/pss/protocol.go
@@ -172,6 +172,8 @@ func (p *Protocol) Handle(msg []byte, peer *p2p.Peer, asymmetric bool, keyid str
rw, err := p.AddPeer(peer, *p.topic, asymmetric, keyid)
if err != nil {
return err
+ } else if rw == nil {
+ return fmt.Errorf("handle called on nil MsgReadWriter for new key " + keyid)
}
vrw = rw.(*PssReadWriter)
}
@@ -181,8 +183,14 @@ func (p *Protocol) Handle(msg []byte, peer *p2p.Peer, asymmetric bool, keyid str
return fmt.Errorf("could not decode pssmsg")
}
if asymmetric {
+ if p.pubKeyRWPool[keyid] == nil {
+ return fmt.Errorf("handle called on nil MsgReadWriter for key " + keyid)
+ }
vrw = p.pubKeyRWPool[keyid].(*PssReadWriter)
} else {
+ if p.symKeyRWPool[keyid] == nil {
+ return fmt.Errorf("handle called on nil MsgReadWriter for key " + keyid)
+ }
vrw = p.symKeyRWPool[keyid].(*PssReadWriter)
}
vrw.injectMsg(pmsg)
diff --git a/swarm/pss/pss.go b/swarm/pss/pss.go
index 77191b25a..dd081e93a 100644
--- a/swarm/pss/pss.go
+++ b/swarm/pss/pss.go
@@ -41,7 +41,7 @@ import (
const (
defaultPaddingByteSize = 16
- defaultMsgTTL = time.Second * 120
+ DefaultMsgTTL = time.Second * 120
defaultDigestCacheTTL = time.Second * 10
defaultSymKeyCacheCapacity = 512
digestLength = 32 // byte length of digest used for pss cache (currently same as swarm chunk hash)
@@ -94,7 +94,7 @@ type PssParams struct {
// Sane defaults for Pss
func NewPssParams() *PssParams {
return &PssParams{
- MsgTTL: defaultMsgTTL,
+ MsgTTL: DefaultMsgTTL,
CacheTTL: defaultDigestCacheTTL,
SymKeyCacheCapacity: defaultSymKeyCacheCapacity,
}
@@ -354,11 +354,11 @@ func (p *Pss) handlePssMsg(msg interface{}) error {
}
if int64(pssmsg.Expire) < time.Now().Unix() {
metrics.GetOrRegisterCounter("pss.expire", nil).Inc(1)
- log.Warn("pss filtered expired message", "from", fmt.Sprintf("%x", p.Overlay.BaseAddr()), "to", fmt.Sprintf("%x", common.ToHex(pssmsg.To)))
+ log.Warn("pss filtered expired message", "from", common.ToHex(p.Overlay.BaseAddr()), "to", common.ToHex(pssmsg.To))
return nil
}
if p.checkFwdCache(pssmsg) {
- log.Trace(fmt.Sprintf("pss relay block-cache match (process): FROM %x TO %x", p.Overlay.BaseAddr(), common.ToHex(pssmsg.To)))
+ log.Trace("pss relay block-cache match (process)", "from", common.ToHex(p.Overlay.BaseAddr()), "to", (common.ToHex(pssmsg.To)))
return nil
}
p.addFwdCache(pssmsg)
@@ -480,7 +480,7 @@ func (p *Pss) SetPeerPublicKey(pubkey *ecdsa.PublicKey, topic Topic, address *Ps
}
// Automatically generate a new symkey for a topic and address hint
-func (p *Pss) generateSymmetricKey(topic Topic, address *PssAddress, addToCache bool) (string, error) {
+func (p *Pss) GenerateSymmetricKey(topic Topic, address *PssAddress, addToCache bool) (string, error) {
keyid, err := p.w.GenerateSymKey()
if err != nil {
return "", err
diff --git a/swarm/pss/pss_test.go b/swarm/pss/pss_test.go
index a59a5e427..c738247f1 100644
--- a/swarm/pss/pss_test.go
+++ b/swarm/pss/pss_test.go
@@ -470,7 +470,7 @@ func TestKeys(t *testing.T) {
}
// make a symmetric key that we will send to peer for encrypting messages to us
- inkeyid, err := ps.generateSymmetricKey(topicobj, &addr, true)
+ inkeyid, err := ps.GenerateSymmetricKey(topicobj, &addr, true)
if err != nil {
t.Fatalf("failed to set 'our' incoming symmetric key")
}
@@ -1296,7 +1296,7 @@ func benchmarkSymKeySend(b *testing.B) {
topic := BytesToTopic([]byte("foo"))
to := make(PssAddress, 32)
copy(to[:], network.RandomAddr().Over())
- symkeyid, err := ps.generateSymmetricKey(topic, &to, true)
+ symkeyid, err := ps.GenerateSymmetricKey(topic, &to, true)
if err != nil {
b.Fatalf("could not generate symkey: %v", err)
}
@@ -1389,7 +1389,7 @@ func benchmarkSymkeyBruteforceChangeaddr(b *testing.B) {
for i := 0; i < int(keycount); i++ {
to := make(PssAddress, 32)
copy(to[:], network.RandomAddr().Over())
- keyid, err = ps.generateSymmetricKey(topic, &to, true)
+ keyid, err = ps.GenerateSymmetricKey(topic, &to, true)
if err != nil {
b.Fatalf("cant generate symkey #%d: %v", i, err)
}
@@ -1471,7 +1471,7 @@ func benchmarkSymkeyBruteforceSameaddr(b *testing.B) {
topic := BytesToTopic([]byte("foo"))
for i := 0; i < int(keycount); i++ {
copy(addr[i], network.RandomAddr().Over())
- keyid, err = ps.generateSymmetricKey(topic, &addr[i], true)
+ keyid, err = ps.GenerateSymmetricKey(topic, &addr[i], true)
if err != nil {
b.Fatalf("cant generate symkey #%d: %v", i, err)
}