Skip to content

Commit 2f5b6cb

Browse files
nolashzelig
authored andcommitted
swarm/network: Use different privatekey for bzz overlay in sim (#19313)
* cmd/swarm, p2p, swarm: Enable ENR in binary/execadapter * cmd/p2p/swarm: Remove comments + config.Enode nomarshal * p2p/simulations: Remove superfluous error check * p2p/simulation: Move init enode comment * swarm, p2p/simulations, cmd/swarm: Use nodekey in binary record sign * swarm/network, swarm/pss: Dervice bzzkey * swarm/pss: Remove unused function * swarm/network: Store swarm private key in simulation bucket * swarm/pss: Shorten TextProxNetwork shortrunning test timeout * swarm/pss: Increase prox test timeout * swarm/pss: Increase timeout slightly on shortrunning proxtest * swarm/network: Simplify bucket instantiation in servicectx func * p2p/simulations: Tcpport -> udpport * swarm/network, swarm/pss: Simplify + correct lock in servicefunc sim * swarm/network: Cleanup after rebase on extract swarm enode new * p2p/simulations, swarm/network: Make exec disc test pass * swarm/network: Prune ye olde comment * swarm/pss: Correct revised bzzkey method call * swarm/network: Clarify comment about privatekey generation data * swarm/pss: Fix syntax errors after rebase * swarm/network: Rename misleadingly named method (amend commit to trigger ci - attempt 5)
1 parent 876f357 commit 2f5b6cb

6 files changed

Lines changed: 97 additions & 39 deletions

File tree

‎p2p/simulations/adapters/exec.go‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -411,14 +411,13 @@ func startExecNodeStack() (*node.Node, error) {
411411
if err := json.Unmarshal([]byte(confEnv), &conf); err != nil {
412412
return nil, fmt.Errorf("error decoding %s: %v", envNodeConfig, err)
413413
}
414-
// TODO verify that ListenAddr will contain the correct tcp addr
415-
// if we should start using exec adapters with other host than local
414+
415+
// create enode record
416416
nodeTcpConn, err := net.ResolveTCPAddr("tcp", conf.Stack.P2P.ListenAddr)
417-
if err != nil {
418-
conf.Node.initDummyEnode()
419-
} else {
420-
conf.Node.initEnode(nodeTcpConn.IP, nodeTcpConn.Port, nodeTcpConn.Port)
417+
if nodeTcpConn.IP == nil {
418+
nodeTcpConn.IP = net.IPv4(127, 0, 0, 1)
421419
}
420+
conf.Node.initEnode(nodeTcpConn.IP, nodeTcpConn.Port, nodeTcpConn.Port)
422421
conf.Stack.P2P.PrivateKey = conf.Node.PrivateKey
423422
conf.Stack.Logger = log.New("node.id", conf.Node.ID.String())
424423

‎p2p/simulations/adapters/types.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ func (n *NodeConfig) initEnode(ip net.IP, tcpport int, udpport int) error {
274274
n.Record.Set(&enrIp)
275275
enrTcpPort := enr.TCP(tcpport)
276276
n.Record.Set(&enrTcpPort)
277-
enrUdpPort := enr.UDP(tcpport)
277+
enrUdpPort := enr.UDP(udpport)
278278
n.Record.Set(&enrUdpPort)
279279

280280
err := enode.SignV4(&n.Record, n.PrivateKey)

‎swarm/network/simulation/node.go‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,28 @@
1717
package simulation
1818

1919
import (
20+
"bytes"
2021
"context"
22+
"crypto/ecdsa"
2123
"encoding/json"
2224
"errors"
2325
"io/ioutil"
2426
"math/rand"
2527
"os"
28+
"sync"
2629
"time"
2730

31+
"github.com/ethereum/go-ethereum/crypto"
2832
"github.com/ethereum/go-ethereum/p2p/enode"
2933
"github.com/ethereum/go-ethereum/p2p/simulations"
3034
"github.com/ethereum/go-ethereum/p2p/simulations/adapters"
3135
"github.com/ethereum/go-ethereum/swarm/network"
3236
)
3337

38+
var (
39+
BucketKeyBzzPrivateKey BucketKey = "bzzprivkey"
40+
)
41+
3442
// NodeIDs returns NodeIDs for all nodes in the network.
3543
func (s *Simulation) NodeIDs() (ids []enode.ID) {
3644
nodes := s.Net.GetNodes()
@@ -104,20 +112,24 @@ func (s *Simulation) AddNode(opts ...AddNodeOption) (id enode.ID, err error) {
104112
// for now we have no way of setting bootnodes or lightnodes in sims
105113
// so we just let them be set to false
106114
// they should perhaps be possible to override them with AddNodeOption
107-
enodeParams := &network.EnodeParams{
108-
PrivateKey: conf.PrivateKey,
109-
}
110-
record, err := network.NewEnodeRecord(enodeParams)
115+
bzzPrivateKey, err := BzzPrivateKeyFromConfig(conf)
111116
if err != nil {
112117
return enode.ID{}, err
113118
}
119+
120+
enodeParams := &network.EnodeParams{
121+
PrivateKey: bzzPrivateKey,
122+
}
123+
record, err := network.NewEnodeRecord(enodeParams)
114124
conf.Record = *record
115125

116126
// Add the bzz address to the node config
117127
node, err := s.Net.NewNodeWithConfig(conf)
118128
if err != nil {
119129
return id, err
120130
}
131+
s.buckets[node.ID()] = new(sync.Map)
132+
s.SetNodeItem(node.ID(), BucketKeyBzzPrivateKey, bzzPrivateKey)
121133

122134
return node.ID(), s.Net.Start(node.ID())
123135
}
@@ -315,3 +327,15 @@ func (s *Simulation) StopRandomNodes(count int) (ids []enode.ID, err error) {
315327
func init() {
316328
rand.Seed(time.Now().UnixNano())
317329
}
330+
331+
// derive a private key for swarm for the node key
332+
// returns the private key used to generate the bzz key
333+
func BzzPrivateKeyFromConfig(conf *adapters.NodeConfig) (*ecdsa.PrivateKey, error) {
334+
// pad the seed key some arbitrary data as ecdsa.GenerateKey takes 40 bytes seed data
335+
privKeyBuf := append(crypto.FromECDSA(conf.PrivateKey), []byte{0x62, 0x7a, 0x7a, 0x62, 0x7a, 0x7a, 0x62, 0x7a}...)
336+
bzzPrivateKey, err := ecdsa.GenerateKey(crypto.S256(), bytes.NewReader(privKeyBuf))
337+
if err != nil {
338+
return nil, err
339+
}
340+
return bzzPrivateKey, nil
341+
}

‎swarm/network/simulation/simulation.go‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,13 +85,16 @@ func New(services map[string]ServiceFunc) (s *Simulation) {
8585
name, serviceFunc := name, serviceFunc
8686
s.serviceNames = append(s.serviceNames, name)
8787
adapterServices[name] = func(ctx *adapters.ServiceContext) (node.Service, error) {
88-
b := new(sync.Map)
88+
s.mu.Lock()
89+
defer s.mu.Unlock()
90+
b, ok := s.buckets[ctx.Config.ID]
91+
if !ok {
92+
b = new(sync.Map)
93+
}
8994
service, cleanup, err := serviceFunc(ctx, b)
9095
if err != nil {
9196
return nil, err
9297
}
93-
s.mu.Lock()
94-
defer s.mu.Unlock()
9598
if cleanup != nil {
9699
s.cleanupFuncs = append(s.cleanupFuncs, cleanup)
97100
}

‎swarm/network/simulations/discovery/discovery_test.go‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,6 @@ func BenchmarkDiscovery_128_4(b *testing.B) { benchmarkDiscovery(b, 128, 4) }
131131
func BenchmarkDiscovery_256_4(b *testing.B) { benchmarkDiscovery(b, 256, 4) }
132132

133133
func TestDiscoverySimulationExecAdapter(t *testing.T) {
134-
t.Skip("This is left broken pending ENR preparations for swarm binary. Execadapter is not currently in use, so a short pause won't hurt")
135134
testDiscoverySimulationExecAdapter(t, *nodeCount, *initCount)
136135
}
137136

‎swarm/pss/prox_test.go‎

Lines changed: 57 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package pss
22

33
import (
44
"context"
5+
"crypto/ecdsa"
56
"encoding/binary"
67
"errors"
78
"fmt"
@@ -88,7 +89,7 @@ func (d *testData) setDone() {
8889
d.handlerDone = true
8990
}
9091

91-
func getCmdParams(t *testing.T) (int, int) {
92+
func getCmdParams(t *testing.T) (int, int, time.Duration) {
9293
args := strings.Split(t.Name(), "/")
9394
msgCount, err := strconv.ParseInt(args[2], 10, 16)
9495
if err != nil {
@@ -98,7 +99,12 @@ func getCmdParams(t *testing.T) (int, int) {
9899
if err != nil {
99100
t.Fatal(err)
100101
}
101-
return int(msgCount), int(nodeCount)
102+
timeoutStr := fmt.Sprintf("%ss", args[3])
103+
timeoutDur, err := time.ParseDuration(timeoutStr)
104+
if err != nil {
105+
t.Fatal(err)
106+
}
107+
return int(msgCount), int(nodeCount), timeoutDur
102108
}
103109

104110
func newTestData() *testData {
@@ -117,11 +123,27 @@ func newTestData() *testData {
117123
}
118124
}
119125

120-
func (d *testData) init(msgCount int) {
126+
func (d *testData) getKademlia(nodeId *enode.ID) (*network.Kademlia, error) {
127+
kadif, ok := d.sim.NodeItem(*nodeId, simulation.BucketKeyKademlia)
128+
if !ok {
129+
return nil, fmt.Errorf("no kademlia entry for %v", nodeId)
130+
}
131+
kad, ok := kadif.(*network.Kademlia)
132+
if !ok {
133+
return nil, fmt.Errorf("invalid kademlia entry for %v", nodeId)
134+
}
135+
return kad, nil
136+
}
137+
138+
func (d *testData) init(msgCount int) error {
121139
log.Debug("TestProxNetwork start")
122140

123141
for _, nodeId := range d.sim.NodeIDs() {
124-
d.nodeAddrs[nodeId] = nodeIDToAddr(nodeId)
142+
kad, err := d.getKademlia(&nodeId)
143+
if err != nil {
144+
return err
145+
}
146+
d.nodeAddrs[nodeId] = kad.BaseAddr()
125147
}
126148

127149
for i := 0; i < int(msgCount); i++ {
@@ -169,6 +191,7 @@ func (d *testData) init(msgCount int) {
169191
log.Debug("nn for msg", "targets", len(d.recipients[i]), "msgidx", i, "msg", common.Bytes2Hex(msgAddr[:8]), "sender", d.senders[i], "senderpo", smallestPo)
170192
}
171193
log.Debug("msgs to receive", "count", d.requiredMessages)
194+
return nil
172195
}
173196

174197
// Here we test specific functionality of the pss, setting the prox property of
@@ -190,37 +213,40 @@ func (d *testData) init(msgCount int) {
190213
// nodes Y and Z will be considered required recipients of the msg,
191214
// whereas nodes X, Y and Z will be allowed recipients.
192215
func TestProxNetwork(t *testing.T) {
193-
t.Run("16/16", testProxNetwork)
216+
t.Run("16/16/15", testProxNetwork)
194217
}
195218

196219
// params in run name: nodes/msgs
197220
func TestProxNetworkLong(t *testing.T) {
198221
if !*longrunning {
199222
t.Skip("run with --longrunning flag to run extensive network tests")
200223
}
201-
t.Run("8/100", testProxNetwork)
202-
t.Run("16/100", testProxNetwork)
203-
t.Run("32/100", testProxNetwork)
204-
t.Run("64/100", testProxNetwork)
205-
t.Run("128/100", testProxNetwork)
224+
t.Run("8/100/30", testProxNetwork)
225+
t.Run("16/100/30", testProxNetwork)
226+
t.Run("32/100/60", testProxNetwork)
227+
t.Run("64/100/60", testProxNetwork)
228+
t.Run("128/100/120", testProxNetwork)
206229
}
207230

208231
func testProxNetwork(t *testing.T) {
209232
tstdata := newTestData()
210-
msgCount, nodeCount := getCmdParams(t)
233+
msgCount, nodeCount, timeout := getCmdParams(t)
211234
handlerContextFuncs := make(map[Topic]handlerContextFunc)
212235
handlerContextFuncs[topic] = nodeMsgHandler
213236
services := newProxServices(tstdata, true, handlerContextFuncs, tstdata.kademlias)
214237
tstdata.sim = simulation.New(services)
215238
defer tstdata.sim.Close()
216-
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
239+
ctx, cancel := context.WithTimeout(context.Background(), timeout)
217240
defer cancel()
218241
filename := fmt.Sprintf("testdata/snapshot_%d.json", nodeCount)
219242
err := tstdata.sim.UploadSnapshot(ctx, filename)
220243
if err != nil {
221244
t.Fatal(err)
222245
}
223-
tstdata.init(msgCount) // initialize the test data
246+
err = tstdata.init(msgCount) // initialize the test data
247+
if err != nil {
248+
t.Fatal(err)
249+
}
224250
wrapper := func(c context.Context, _ *simulation.Simulation) error {
225251
return testRoutine(tstdata, c)
226252
}
@@ -230,7 +256,7 @@ func testProxNetwork(t *testing.T) {
230256
// however, it might just mean that not all possible messages are received
231257
// now we must check if all required messages are received
232258
cnt := tstdata.getMsgCount()
233-
log.Debug("TestProxNetwork finnished", "rcv", cnt)
259+
log.Debug("TestProxNetwork finished", "rcv", cnt)
234260
if cnt < tstdata.requiredMessages {
235261
t.Fatal(result.Error)
236262
}
@@ -354,7 +380,7 @@ func nodeMsgHandler(tstdata *testData, config *adapters.NodeConfig) *handler {
354380
// replaces pss_test.go when those tests are rewritten to the new swarm/network/simulation package
355381
func newProxServices(tstdata *testData, allowRaw bool, handlerContextFuncs map[Topic]handlerContextFunc, kademlias map[enode.ID]*network.Kademlia) map[string]simulation.ServiceFunc {
356382
stateStore := state.NewInmemoryStore()
357-
kademlia := func(id enode.ID) *network.Kademlia {
383+
kademlia := func(id enode.ID, bzzkey []byte) *network.Kademlia {
358384
if k, ok := kademlias[id]; ok {
359385
return k
360386
}
@@ -364,25 +390,32 @@ func newProxServices(tstdata *testData, allowRaw bool, handlerContextFuncs map[T
364390
params.MaxRetries = 1000
365391
params.RetryExponent = 2
366392
params.RetryInterval = 1000000
367-
kademlias[id] = network.NewKademlia(id[:], params)
393+
kademlias[id] = network.NewKademlia(bzzkey, params)
368394
return kademlias[id]
369395
}
370396
return map[string]simulation.ServiceFunc{
371397
"bzz": func(ctx *adapters.ServiceContext, b *sync.Map) (node.Service, func(), error) {
398+
var err error
399+
var bzzPrivateKey *ecdsa.PrivateKey
372400
// normally translation of enode id to swarm address is concealed by the network package
373401
// however, we need to keep track of it in the test driver as well.
374402
// if the translation in the network package changes, that can cause these tests to unpredictably fail
375403
// therefore we keep a local copy of the translation here
376404
addr := network.NewAddr(ctx.Config.Node())
377-
addr.OAddr = nodeIDToAddr(ctx.Config.Node().ID())
405+
bzzPrivateKey, err = simulation.BzzPrivateKeyFromConfig(ctx.Config)
406+
if err != nil {
407+
return nil, nil, err
408+
}
409+
addr.OAddr = network.PrivateKeyToBzzKey(bzzPrivateKey)
410+
b.Store(simulation.BucketKeyBzzPrivateKey, bzzPrivateKey)
378411
hp := network.NewHiveParams()
379412
hp.Discovery = false
380413
config := &network.BzzConfig{
381414
OverlayAddr: addr.Over(),
382415
UnderlayAddr: addr.Under(),
383416
HiveParams: hp,
384417
}
385-
return network.NewBzz(config, kademlia(ctx.Config.ID), stateStore, nil, nil), nil, nil
418+
return network.NewBzz(config, kademlia(ctx.Config.ID, addr.OAddr), stateStore, nil, nil), nil, nil
386419
},
387420
"pss": func(ctx *adapters.ServiceContext, b *sync.Map) (node.Service, func(), error) {
388421
// execadapter does not exec init()
@@ -395,7 +428,12 @@ func newProxServices(tstdata *testData, allowRaw bool, handlerContextFuncs map[T
395428
privkey, err := w.GetPrivateKey(keys)
396429
pssp := NewPssParams().WithPrivateKey(privkey)
397430
pssp.AllowRaw = allowRaw
398-
pskad := kademlia(ctx.Config.ID)
431+
bzzPrivateKey, err := simulation.BzzPrivateKeyFromConfig(ctx.Config)
432+
if err != nil {
433+
return nil, nil, err
434+
}
435+
bzzKey := network.PrivateKeyToBzzKey(bzzPrivateKey)
436+
pskad := kademlia(ctx.Config.ID, bzzKey)
399437
ps, err := NewPss(pskad, pssp)
400438
if err != nil {
401439
return nil, nil, err
@@ -433,8 +471,3 @@ func newProxServices(tstdata *testData, allowRaw bool, handlerContextFuncs map[T
433471
},
434472
}
435473
}
436-
437-
// makes sure we create the addresses the same way in driver and service setup
438-
func nodeIDToAddr(id enode.ID) []byte {
439-
return id.Bytes()
440-
}

0 commit comments

Comments
 (0)