github.com/puppeth/go-ethereum@v0.8.6-0.20171014130046-e9295163aa25/les/odr.go (about) 1 // Copyright 2016 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 les 18 19 import ( 20 "context" 21 22 "github.com/ethereum/go-ethereum/ethdb" 23 "github.com/ethereum/go-ethereum/light" 24 "github.com/ethereum/go-ethereum/log" 25 ) 26 27 // LesOdr implements light.OdrBackend 28 type LesOdr struct { 29 db ethdb.Database 30 stop chan struct{} 31 retriever *retrieveManager 32 } 33 34 func NewLesOdr(db ethdb.Database, retriever *retrieveManager) *LesOdr { 35 return &LesOdr{ 36 db: db, 37 retriever: retriever, 38 stop: make(chan struct{}), 39 } 40 } 41 42 func (odr *LesOdr) Stop() { 43 close(odr.stop) 44 } 45 46 func (odr *LesOdr) Database() ethdb.Database { 47 return odr.db 48 } 49 50 const ( 51 MsgBlockBodies = iota 52 MsgCode 53 MsgReceipts 54 MsgProofs 55 MsgHeaderProofs 56 ) 57 58 // Msg encodes a LES message that delivers reply data for a request 59 type Msg struct { 60 MsgType int 61 ReqID uint64 62 Obj interface{} 63 } 64 65 // Retrieve tries to fetch an object from the LES network. 66 // If the network retrieval was successful, it stores the object in local db. 67 func (self *LesOdr) Retrieve(ctx context.Context, req light.OdrRequest) (err error) { 68 lreq := LesRequest(req) 69 70 reqID := genReqID() 71 rq := &distReq{ 72 getCost: func(dp distPeer) uint64 { 73 return lreq.GetCost(dp.(*peer)) 74 }, 75 canSend: func(dp distPeer) bool { 76 p := dp.(*peer) 77 return lreq.CanSend(p) 78 }, 79 request: func(dp distPeer) func() { 80 p := dp.(*peer) 81 cost := lreq.GetCost(p) 82 p.fcServer.QueueRequest(reqID, cost) 83 return func() { lreq.Request(reqID, p) } 84 }, 85 } 86 87 if err = self.retriever.retrieve(ctx, reqID, rq, func(p distPeer, msg *Msg) error { return lreq.Validate(self.db, msg) }); err == nil { 88 // retrieved from network, store in db 89 req.StoreResult(self.db) 90 } else { 91 log.Debug("Failed to retrieve data from network", "err", err) 92 } 93 return 94 }