github.com/jincm/wesharechain@v0.0.0-20210122032815-1537409ce26a/chain/swarm/network/stream/syncer.go (about) 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 stream 18 19 import ( 20 "context" 21 "strconv" 22 "time" 23 24 "github.com/ethereum/go-ethereum/metrics" 25 "github.com/ethereum/go-ethereum/swarm/log" 26 "github.com/ethereum/go-ethereum/swarm/storage" 27 ) 28 29 const ( 30 BatchSize = 128 31 ) 32 33 // SwarmSyncerServer implements an Server for history syncing on bins 34 // offered streams: 35 // * live request delivery with or without checkback 36 // * (live/non-live historical) chunk syncing per proximity bin 37 type SwarmSyncerServer struct { 38 po uint8 39 store storage.SyncChunkStore 40 quit chan struct{} 41 } 42 43 // NewSwarmSyncerServer is constructor for SwarmSyncerServer 44 func NewSwarmSyncerServer(po uint8, syncChunkStore storage.SyncChunkStore) (*SwarmSyncerServer, error) { 45 return &SwarmSyncerServer{ 46 po: po, 47 store: syncChunkStore, 48 quit: make(chan struct{}), 49 }, nil 50 } 51 52 func RegisterSwarmSyncerServer(streamer *Registry, syncChunkStore storage.SyncChunkStore) { 53 streamer.RegisterServerFunc("SYNC", func(_ *Peer, t string, _ bool) (Server, error) { 54 po, err := ParseSyncBinKey(t) 55 if err != nil { 56 return nil, err 57 } 58 return NewSwarmSyncerServer(po, syncChunkStore) 59 }) 60 // streamer.RegisterServerFunc(stream, func(p *Peer) (Server, error) { 61 // return NewOutgoingProvableSwarmSyncer(po, db) 62 // }) 63 } 64 65 // Close needs to be called on a stream server 66 func (s *SwarmSyncerServer) Close() { 67 close(s.quit) 68 } 69 70 // GetData retrieves the actual chunk from netstore 71 func (s *SwarmSyncerServer) GetData(ctx context.Context, key []byte) ([]byte, error) { 72 chunk, err := s.store.Get(ctx, storage.Address(key)) 73 if err != nil { 74 return nil, err 75 } 76 return chunk.Data(), nil 77 } 78 79 // SessionIndex returns current storage bin (po) index. 80 func (s *SwarmSyncerServer) SessionIndex() (uint64, error) { 81 return s.store.BinIndex(s.po), nil 82 } 83 84 // GetBatch retrieves the next batch of hashes from the dbstore 85 func (s *SwarmSyncerServer) SetNextBatch(from, to uint64) ([]byte, uint64, uint64, *HandoverProof, error) { 86 var batch []byte 87 i := 0 88 89 var ticker *time.Ticker 90 defer func() { 91 if ticker != nil { 92 ticker.Stop() 93 } 94 }() 95 var wait bool 96 for { 97 if wait { 98 if ticker == nil { 99 ticker = time.NewTicker(1000 * time.Millisecond) 100 } 101 select { 102 case <-ticker.C: 103 case <-s.quit: 104 return nil, 0, 0, nil, nil 105 } 106 } 107 108 metrics.GetOrRegisterCounter("syncer.setnextbatch.iterator", nil).Inc(1) 109 err := s.store.Iterator(from, to, s.po, func(key storage.Address, idx uint64) bool { 110 select { 111 case <-s.quit: 112 return false 113 default: 114 } 115 batch = append(batch, key[:]...) 116 i++ 117 to = idx 118 return i < BatchSize 119 }) 120 if err != nil { 121 return nil, 0, 0, nil, err 122 } 123 if len(batch) > 0 { 124 break 125 } 126 wait = true 127 } 128 129 log.Trace("Swarm syncer offer batch", "po", s.po, "len", i, "from", from, "to", to, "current store count", s.store.BinIndex(s.po)) 130 return batch, from, to, nil, nil 131 } 132 133 // SwarmSyncerClient 134 type SwarmSyncerClient struct { 135 store storage.SyncChunkStore 136 peer *Peer 137 stream Stream 138 } 139 140 // NewSwarmSyncerClient is a contructor for provable data exchange syncer 141 func NewSwarmSyncerClient(p *Peer, store storage.SyncChunkStore, stream Stream) (*SwarmSyncerClient, error) { 142 return &SwarmSyncerClient{ 143 store: store, 144 peer: p, 145 stream: stream, 146 }, nil 147 } 148 149 // // NewIncomingProvableSwarmSyncer is a contructor for provable data exchange syncer 150 // func NewIncomingProvableSwarmSyncer(po int, priority int, index uint64, sessionAt uint64, intervals []uint64, sessionRoot storage.Address, chunker *storage.PyramidChunker, store storage.ChunkStore, p Peer) *SwarmSyncerClient { 151 // retrieveC := make(storage.Chunk, chunksCap) 152 // RunChunkRequestor(p, retrieveC) 153 // storeC := make(storage.Chunk, chunksCap) 154 // RunChunkStorer(store, storeC) 155 // s := &SwarmSyncerClient{ 156 // po: po, 157 // priority: priority, 158 // sessionAt: sessionAt, 159 // start: index, 160 // end: index, 161 // nextC: make(chan struct{}, 1), 162 // intervals: intervals, 163 // sessionRoot: sessionRoot, 164 // sessionReader: chunker.Join(sessionRoot, retrieveC), 165 // retrieveC: retrieveC, 166 // storeC: storeC, 167 // } 168 // return s 169 // } 170 171 // // StartSyncing is called on the Peer to start the syncing process 172 // // the idea is that it is called only after kademlia is close to healthy 173 // func StartSyncing(s *Streamer, peerId enode.ID, po uint8, nn bool) { 174 // lastPO := po 175 // if nn { 176 // lastPO = maxPO 177 // } 178 // 179 // for i := po; i <= lastPO; i++ { 180 // s.Subscribe(peerId, "SYNC", newSyncLabel("LIVE", po), 0, 0, High, true) 181 // s.Subscribe(peerId, "SYNC", newSyncLabel("HISTORY", po), 0, 0, Mid, false) 182 // } 183 // } 184 185 // RegisterSwarmSyncerClient registers the client constructor function for 186 // to handle incoming sync streams 187 func RegisterSwarmSyncerClient(streamer *Registry, store storage.SyncChunkStore) { 188 streamer.RegisterClientFunc("SYNC", func(p *Peer, t string, live bool) (Client, error) { 189 return NewSwarmSyncerClient(p, store, NewStream("SYNC", t, live)) 190 }) 191 } 192 193 // NeedData 194 func (s *SwarmSyncerClient) NeedData(ctx context.Context, key []byte) (wait func(context.Context) error) { 195 return s.store.FetchFunc(ctx, key) 196 } 197 198 // BatchDone 199 func (s *SwarmSyncerClient) BatchDone(stream Stream, from uint64, hashes []byte, root []byte) func() (*TakeoverProof, error) { 200 // TODO: reenable this with putter/getter refactored code 201 // if s.chunker != nil { 202 // return func() (*TakeoverProof, error) { return s.TakeoverProof(stream, from, hashes, root) } 203 // } 204 return nil 205 } 206 207 func (s *SwarmSyncerClient) Close() {} 208 209 // base for parsing and formating sync bin key 210 // it must be 2 <= base <= 36 211 const syncBinKeyBase = 36 212 213 // FormatSyncBinKey returns a string representation of 214 // Kademlia bin number to be used as key for SYNC stream. 215 func FormatSyncBinKey(bin uint8) string { 216 return strconv.FormatUint(uint64(bin), syncBinKeyBase) 217 } 218 219 // ParseSyncBinKey parses the string representation 220 // and returns the Kademlia bin number. 221 func ParseSyncBinKey(s string) (uint8, error) { 222 bin, err := strconv.ParseUint(s, syncBinKeyBase, 8) 223 if err != nil { 224 return 0, err 225 } 226 return uint8(bin), nil 227 }