Skip to content

Commit ffe2fc3

Browse files
holisticodezelig
authored andcommitted
Swarm accounting (#18050)
* swarm: completed 1st phase of swap accounting * swarm: swap accounting for swarm with p2p accounting * swarm/swap: addressed PR comments * swarm/swap: ignore ErrNotFound on stateStore.Get() * swarm/swap: GetPeerBalance test; add TODO for chequebook API check * swarm/network/stream: fix NewRegistry calls with new arguments * swarm/swap: address @justelad's PR comments
1 parent 3240276 commit ffe2fc3

10 files changed

Lines changed: 353 additions & 38 deletions

File tree

‎swarm/network/stream/common_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ func newStreamerTester(t *testing.T, registryOptions *RegistryOptions) (*p2ptest
114114

115115
delivery := NewDelivery(to, netStore)
116116
netStore.NewNetFetcherFunc = network.NewFetcherFactory(delivery.RequestFromPeers, true).New
117-
streamer := NewRegistry(addr.ID(), delivery, netStore, state.NewInmemoryStore(), registryOptions)
117+
streamer := NewRegistry(addr.ID(), delivery, netStore, state.NewInmemoryStore(), registryOptions, nil)
118118
teardown := func() {
119119
streamer.Close()
120120
removeDataDir()

‎swarm/network/stream/delivery_test.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ func TestRequestFromPeers(t *testing.T) {
290290
Peer: protocolsPeer,
291291
}, to)
292292
to.On(peer)
293-
r := NewRegistry(addr.ID(), delivery, nil, nil, nil)
293+
r := NewRegistry(addr.ID(), delivery, nil, nil, nil, nil)
294294

295295
// an empty priorityQueue has to be created to prevent a goroutine being called after the test has finished
296296
sp := &Peer{
@@ -331,7 +331,7 @@ func TestRequestFromPeersWithLightNode(t *testing.T) {
331331
Peer: protocolsPeer,
332332
}, to)
333333
to.On(peer)
334-
r := NewRegistry(addr.ID(), delivery, nil, nil, nil)
334+
r := NewRegistry(addr.ID(), delivery, nil, nil, nil, nil)
335335
// an empty priorityQueue has to be created to prevent a goroutine being called after the test has finished
336336
sp := &Peer{
337337
Peer: protocolsPeer,
@@ -480,7 +480,7 @@ func testDeliveryFromNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck
480480
SkipCheck: skipCheck,
481481
Syncing: SyncingDisabled,
482482
Retrieval: RetrievalEnabled,
483-
})
483+
}, nil)
484484
bucket.Store(bucketKeyRegistry, r)
485485

486486
fileStore := storage.NewFileStore(netStore, storage.NewFileStoreParams())
@@ -655,7 +655,7 @@ func benchmarkDeliveryFromNodes(b *testing.B, nodes, conns, chunkCount int, skip
655655
Syncing: SyncingDisabled,
656656
Retrieval: RetrievalDisabled,
657657
SyncUpdateDelay: 0,
658-
})
658+
}, nil)
659659

660660
fileStore := storage.NewFileStore(netStore, storage.NewFileStoreParams())
661661
bucket.Store(bucketKeyFileStore, fileStore)

‎swarm/network/stream/intervals_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ func testIntervals(t *testing.T, live bool, history *Range, skipCheck bool) {
8484
Retrieval: RetrievalDisabled,
8585
Syncing: SyncingRegisterOnly,
8686
SkipCheck: skipCheck,
87-
})
87+
}, nil)
8888
bucket.Store(bucketKeyRegistry, r)
8989

9090
r.RegisterClientFunc(externalStreamName, func(p *Peer, t string, live bool) (Client, error) {

‎swarm/network/stream/snapshot_retrieval_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ func retrievalStreamerFunc(ctx *adapters.ServiceContext, bucket *sync.Map) (s no
130130
Retrieval: RetrievalEnabled,
131131
Syncing: SyncingAutoSubscribe,
132132
SyncUpdateDelay: 3 * time.Second,
133-
})
133+
}, nil)
134134

135135
fileStore := storage.NewFileStore(netStore, storage.NewFileStoreParams())
136136
bucket.Store(bucketKeyFileStore, fileStore)

‎swarm/network/stream/snapshot_sync_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ func streamerFunc(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Servic
166166
Retrieval: RetrievalDisabled,
167167
Syncing: SyncingAutoSubscribe,
168168
SyncUpdateDelay: 3 * time.Second,
169-
})
169+
}, nil)
170170

171171
bucket.Store(bucketKeyRegistry, r)
172172

@@ -360,7 +360,7 @@ func testSyncingViaDirectSubscribe(t *testing.T, chunkCount int, nodeCount int)
360360
r := NewRegistry(addr.ID(), delivery, netStore, state.NewInmemoryStore(), &RegistryOptions{
361361
Retrieval: RetrievalDisabled,
362362
Syncing: SyncingRegisterOnly,
363-
})
363+
}, nil)
364364
bucket.Store(bucketKeyRegistry, r)
365365

366366
fileStore := storage.NewFileStore(netStore, storage.NewFileStoreParams())

‎swarm/network/stream/stream.go‎

Lines changed: 51 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"errors"
2222
"fmt"
2323
"math"
24+
"reflect"
2425
"sync"
2526
"time"
2627

@@ -87,6 +88,9 @@ type Registry struct {
8788
intervalsStore state.Store
8889
autoRetrieval bool //automatically subscribe to retrieve request stream
8990
maxPeerServers int
91+
spec *protocols.Spec //this protocol's spec
92+
balance protocols.Balance //implements protocols.Balance, for accounting
93+
prices protocols.Prices //implements protocols.Prices, provides prices to accounting
9094
}
9195

9296
// RegistryOptions holds optional values for NewRegistry constructor.
@@ -99,7 +103,7 @@ type RegistryOptions struct {
99103
}
100104

101105
// NewRegistry is Streamer constructor
102-
func NewRegistry(localID enode.ID, delivery *Delivery, syncChunkStore storage.SyncChunkStore, intervalsStore state.Store, options *RegistryOptions) *Registry {
106+
func NewRegistry(localID enode.ID, delivery *Delivery, syncChunkStore storage.SyncChunkStore, intervalsStore state.Store, options *RegistryOptions, balance protocols.Balance) *Registry {
103107
if options == nil {
104108
options = &RegistryOptions{}
105109
}
@@ -119,7 +123,10 @@ func NewRegistry(localID enode.ID, delivery *Delivery, syncChunkStore storage.Sy
119123
intervalsStore: intervalsStore,
120124
autoRetrieval: retrieval,
121125
maxPeerServers: options.MaxPeerServers,
126+
balance: balance,
122127
}
128+
streamer.setupSpec()
129+
123130
streamer.api = NewAPI(streamer)
124131
delivery.getPeer = streamer.getPeer
125132

@@ -228,6 +235,17 @@ func NewRegistry(localID enode.ID, delivery *Delivery, syncChunkStore storage.Sy
228235
return streamer
229236
}
230237

238+
//we need to construct a spec instance per node instance
239+
func (r *Registry) setupSpec() {
240+
//first create the "bare" spec
241+
r.createSpec()
242+
//if balance is nil, this node has been started without swap support (swapEnabled flag is false)
243+
if r.balance != nil && !reflect.ValueOf(r.balance).IsNil() {
244+
//swap is enabled, so setup the hook
245+
r.spec.Hook = protocols.NewAccounting(r.balance, r.prices)
246+
}
247+
}
248+
231249
// RegisterClient registers an incoming streamer constructor
232250
func (r *Registry) RegisterClientFunc(stream string, f func(*Peer, string, bool) (Client, error)) {
233251
r.clientMu.Lock()
@@ -492,7 +510,7 @@ func (r *Registry) updateSyncing() {
492510
}
493511

494512
func (r *Registry) runProtocol(p *p2p.Peer, rw p2p.MsgReadWriter) error {
495-
peer := protocols.NewPeer(p, rw, Spec)
513+
peer := protocols.NewPeer(p, rw, r.spec)
496514
bp := network.NewBzzPeer(peer)
497515
np := network.NewPeer(bp, r.delivery.kad)
498516
r.delivery.kad.On(np)
@@ -716,35 +734,43 @@ func (c *clientParams) clientCreated() {
716734
close(c.clientCreatedC)
717735
}
718736

719-
// Spec is the spec of the streamer protocol
720-
var Spec = &protocols.Spec{
721-
Name: "stream",
722-
Version: 8,
723-
MaxMsgSize: 10 * 1024 * 1024,
724-
Messages: []interface{}{
725-
UnsubscribeMsg{},
726-
OfferedHashesMsg{},
727-
WantedHashesMsg{},
728-
TakeoverProofMsg{},
729-
SubscribeMsg{},
730-
RetrieveRequestMsg{},
731-
ChunkDeliveryMsgRetrieval{},
732-
SubscribeErrorMsg{},
733-
RequestSubscriptionMsg{},
734-
QuitMsg{},
735-
ChunkDeliveryMsgSyncing{},
736-
},
737+
//GetSpec returns the streamer spec to callers
738+
//This used to be a global variable but for simulations with
739+
//multiple nodes its fields (notably the Hook) would be overwritten
740+
func (r *Registry) GetSpec() *protocols.Spec {
741+
return r.spec
742+
}
743+
744+
func (r *Registry) createSpec() {
745+
// Spec is the spec of the streamer protocol
746+
var spec = &protocols.Spec{
747+
Name: "stream",
748+
Version: 8,
749+
MaxMsgSize: 10 * 1024 * 1024,
750+
Messages: []interface{}{
751+
UnsubscribeMsg{},
752+
OfferedHashesMsg{},
753+
WantedHashesMsg{},
754+
TakeoverProofMsg{},
755+
SubscribeMsg{},
756+
RetrieveRequestMsg{},
757+
ChunkDeliveryMsgRetrieval{},
758+
SubscribeErrorMsg{},
759+
RequestSubscriptionMsg{},
760+
QuitMsg{},
761+
ChunkDeliveryMsgSyncing{},
762+
},
763+
}
764+
r.spec = spec
737765
}
738766

739767
func (r *Registry) Protocols() []p2p.Protocol {
740768
return []p2p.Protocol{
741769
{
742-
Name: Spec.Name,
743-
Version: Spec.Version,
744-
Length: Spec.Length(),
770+
Name: r.spec.Name,
771+
Version: r.spec.Version,
772+
Length: r.spec.Length(),
745773
Run: r.runProtocol,
746-
// NodeInfo: ,
747-
// PeerInfo: ,
748774
},
749775
}
750776
}

‎swarm/network/stream/syncer_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ func testSyncBetweenNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck
118118
Retrieval: RetrievalDisabled,
119119
Syncing: SyncingAutoSubscribe,
120120
SkipCheck: skipCheck,
121-
})
121+
}, nil)
122122

123123
fileStore := storage.NewFileStore(netStore, storage.NewFileStoreParams())
124124
bucket.Store(bucketKeyFileStore, fileStore)

‎swarm/swap/swap.go‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
// Copyright 2018 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package swap
18+
19+
import (
20+
"errors"
21+
"fmt"
22+
"strconv"
23+
"sync"
24+
25+
"github.com/ethereum/go-ethereum/p2p/enode"
26+
"github.com/ethereum/go-ethereum/p2p/protocols"
27+
"github.com/ethereum/go-ethereum/swarm/log"
28+
"github.com/ethereum/go-ethereum/swarm/state"
29+
)
30+
31+
// SwAP Swarm Accounting Protocol
32+
// a peer to peer micropayment system
33+
// A node maintains an individual balance with every peer
34+
// Only messages which have a price will be accounted for
35+
type Swap struct {
36+
stateStore state.Store //stateStore is needed in order to keep balances across sessions
37+
lock sync.RWMutex //lock the balances
38+
balances map[enode.ID]int64 //map of balances for each peer
39+
}
40+
41+
// New - swap constructor
42+
func New(stateStore state.Store) (swap *Swap) {
43+
swap = &Swap{
44+
stateStore: stateStore,
45+
balances: make(map[enode.ID]int64),
46+
}
47+
return
48+
}
49+
50+
//Swap implements the protocols.Balance interface
51+
//Add is the (sole) accounting function
52+
func (s *Swap) Add(amount int64, peer *protocols.Peer) (err error) {
53+
s.lock.Lock()
54+
defer s.lock.Unlock()
55+
56+
//load existing balances from the state store
57+
err = s.loadState(peer)
58+
if err != nil && err != state.ErrNotFound {
59+
return
60+
}
61+
//adjust the balance
62+
//if amount is negative, it will decrease, otherwise increase
63+
s.balances[peer.ID()] += amount
64+
//save the new balance to the state store
65+
peerBalance := s.balances[peer.ID()]
66+
err = s.stateStore.Put(peer.ID().String(), &peerBalance)
67+
68+
log.Debug(fmt.Sprintf("balance for peer %s: %s", peer.ID().String(), strconv.FormatInt(peerBalance, 10)))
69+
return err
70+
}
71+
72+
//GetPeerBalance returns the balance for a given peer
73+
func (swap *Swap) GetPeerBalance(peer enode.ID) (int64, error) {
74+
swap.lock.RLock()
75+
defer swap.lock.RUnlock()
76+
if p, ok := swap.balances[peer]; ok {
77+
return p, nil
78+
}
79+
return 0, errors.New("Peer not found")
80+
}
81+
82+
//load balances from the state store (persisted)
83+
func (s *Swap) loadState(peer *protocols.Peer) (err error) {
84+
var peerBalance int64
85+
peerID := peer.ID()
86+
//only load if the current instance doesn't already have this peer's
87+
//balance in memory
88+
if _, ok := s.balances[peerID]; !ok {
89+
err = s.stateStore.Get(peerID.String(), &peerBalance)
90+
s.balances[peerID] = peerBalance
91+
}
92+
return
93+
}

0 commit comments

Comments
 (0)