2019-11-10 19:33:08 +00:00
|
|
|
package blocksync
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"math/rand"
|
|
|
|
"sort"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
blocks "github.com/ipfs/go-block-format"
|
|
|
|
bserv "github.com/ipfs/go-blockservice"
|
|
|
|
"github.com/ipfs/go-cid"
|
2020-03-19 04:13:04 +00:00
|
|
|
graphsync "github.com/ipfs/go-graphsync"
|
|
|
|
gsnet "github.com/ipfs/go-graphsync/network"
|
2019-12-05 02:04:09 +00:00
|
|
|
host "github.com/libp2p/go-libp2p-core/host"
|
2019-11-10 19:33:08 +00:00
|
|
|
inet "github.com/libp2p/go-libp2p-core/network"
|
|
|
|
"github.com/libp2p/go-libp2p-core/peer"
|
|
|
|
"go.opencensus.io/trace"
|
|
|
|
"golang.org/x/xerrors"
|
|
|
|
|
2020-01-22 23:57:42 +00:00
|
|
|
cborutil "github.com/filecoin-project/go-cbor-util"
|
2019-11-10 19:33:08 +00:00
|
|
|
"github.com/filecoin-project/lotus/chain/store"
|
|
|
|
"github.com/filecoin-project/lotus/chain/types"
|
2020-01-22 23:57:42 +00:00
|
|
|
incrt "github.com/filecoin-project/lotus/lib/increadtimeout"
|
2020-02-22 11:36:22 +00:00
|
|
|
"github.com/filecoin-project/lotus/lib/peermgr"
|
2019-11-10 19:33:08 +00:00
|
|
|
"github.com/filecoin-project/lotus/node/modules/dtypes"
|
|
|
|
)
|
|
|
|
|
|
|
|
type BlockSync struct {
|
|
|
|
bserv bserv.BlockService
|
2020-03-19 04:13:04 +00:00
|
|
|
gsync graphsync.GraphExchange
|
2019-11-10 19:33:08 +00:00
|
|
|
host host.Host
|
|
|
|
|
2019-12-05 02:04:09 +00:00
|
|
|
syncPeers *bsPeerTracker
|
2019-12-10 15:02:01 +00:00
|
|
|
peerMgr *peermgr.PeerMgr
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
|
|
|
|
2020-03-19 04:13:04 +00:00
|
|
|
func NewBlockSyncClient(bserv dtypes.ChainBlockService, h host.Host, pmgr peermgr.MaybePeerMgr, gs dtypes.Graphsync) *BlockSync {
|
2019-11-10 19:33:08 +00:00
|
|
|
return &BlockSync{
|
|
|
|
bserv: bserv,
|
|
|
|
host: h,
|
2019-12-10 15:02:01 +00:00
|
|
|
syncPeers: newPeerTracker(pmgr.Mgr),
|
|
|
|
peerMgr: pmgr.Mgr,
|
2020-03-19 04:13:04 +00:00
|
|
|
gsync: gs,
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (bs *BlockSync) processStatus(req *BlockSyncRequest, res *BlockSyncResponse) error {
|
|
|
|
switch res.Status {
|
2020-01-23 22:24:52 +00:00
|
|
|
case StatusPartial: // Partial Response
|
2019-11-16 23:41:14 +00:00
|
|
|
return xerrors.Errorf("not handling partial blocksync responses yet")
|
2020-01-23 22:24:52 +00:00
|
|
|
case StatusNotFound: // req.Start not found
|
2019-11-16 23:41:14 +00:00
|
|
|
return xerrors.Errorf("not found")
|
2020-01-23 22:24:52 +00:00
|
|
|
case StatusGoAway: // Go Away
|
2019-11-16 23:41:14 +00:00
|
|
|
return xerrors.Errorf("not handling 'go away' blocksync responses yet")
|
2020-01-23 22:24:52 +00:00
|
|
|
case StatusInternalError: // Internal Error
|
2019-11-16 23:41:14 +00:00
|
|
|
return xerrors.Errorf("block sync peer errored: %s", res.Message)
|
2020-01-23 22:24:52 +00:00
|
|
|
case StatusBadRequest:
|
2019-11-16 23:41:14 +00:00
|
|
|
return xerrors.Errorf("block sync request invalid: %s", res.Message)
|
2019-11-10 19:33:08 +00:00
|
|
|
default:
|
2019-11-16 23:41:14 +00:00
|
|
|
return xerrors.Errorf("unrecognized response code: %d", res.Status)
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-23 21:51:25 +00:00
|
|
|
// GetBlocks fetches count blocks from the network, from the provided tipset
|
|
|
|
// *backwards*, returning as many tipsets as count.
|
|
|
|
//
|
|
|
|
// {hint/usage}: This is used by the Syncer during normal chain syncing and when
|
|
|
|
// resolving forks.
|
2019-12-16 19:22:56 +00:00
|
|
|
func (bs *BlockSync) GetBlocks(ctx context.Context, tsk types.TipSetKey, count int) ([]*types.TipSet, error) {
|
2019-11-10 19:33:08 +00:00
|
|
|
ctx, span := trace.StartSpan(ctx, "bsync.GetBlocks")
|
|
|
|
defer span.End()
|
|
|
|
if span.IsRecordingEvents() {
|
|
|
|
span.AddAttributes(
|
2019-12-16 19:22:56 +00:00
|
|
|
trace.StringAttribute("tipset", fmt.Sprint(tsk.Cids())),
|
2019-11-10 19:33:08 +00:00
|
|
|
trace.Int64Attribute("count", int64(count)),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
req := &BlockSyncRequest{
|
2019-12-16 19:22:56 +00:00
|
|
|
Start: tsk.Cids(),
|
2019-11-10 19:33:08 +00:00
|
|
|
RequestLength: uint64(count),
|
|
|
|
Options: BSOptBlocks,
|
|
|
|
}
|
|
|
|
|
2020-06-23 21:51:25 +00:00
|
|
|
// this peerset is sorted by latency and failure counting.
|
2019-11-10 23:06:06 +00:00
|
|
|
peers := bs.getPeers()
|
2020-06-23 21:51:25 +00:00
|
|
|
|
2019-12-08 15:02:38 +00:00
|
|
|
// randomize the first few peers so we don't always pick the same peer
|
|
|
|
shufflePrefix(peers)
|
2019-11-10 23:06:06 +00:00
|
|
|
|
2019-12-08 16:24:51 +00:00
|
|
|
start := time.Now()
|
2019-11-10 19:33:08 +00:00
|
|
|
var oerr error
|
2019-12-08 16:24:51 +00:00
|
|
|
|
2019-11-10 23:06:06 +00:00
|
|
|
for _, p := range peers {
|
2019-11-13 17:03:56 +00:00
|
|
|
// TODO: doing this synchronously isnt great, but fetching in parallel
|
|
|
|
// may not be a good idea either. think about this more
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil, xerrors.Errorf("blocksync getblocks failed: %w", ctx.Err())
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2019-11-10 23:06:06 +00:00
|
|
|
res, err := bs.sendRequestToPeer(ctx, p, req)
|
2019-11-10 19:33:08 +00:00
|
|
|
if err != nil {
|
|
|
|
oerr = err
|
2019-12-16 17:14:21 +00:00
|
|
|
if !xerrors.Is(err, inet.ErrNoConn) {
|
|
|
|
log.Warnf("BlockSync request failed for peer %s: %s", p.String(), err)
|
|
|
|
}
|
2019-11-10 19:33:08 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-04-01 18:35:09 +00:00
|
|
|
if res.Status == StatusOK || res.Status == StatusPartial {
|
2019-12-17 06:15:06 +00:00
|
|
|
resp, err := bs.processBlocksResponse(req, res)
|
|
|
|
if err != nil {
|
|
|
|
return nil, xerrors.Errorf("success response from peer failed to process: %w", err)
|
|
|
|
}
|
2019-12-08 16:24:51 +00:00
|
|
|
bs.syncPeers.logGlobalSuccess(time.Since(start))
|
2019-12-17 18:11:26 +00:00
|
|
|
bs.host.ConnManager().TagPeer(p, "bsync", 25)
|
2019-12-17 06:15:06 +00:00
|
|
|
return resp, nil
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
2020-04-01 18:35:09 +00:00
|
|
|
|
2019-11-10 19:33:08 +00:00
|
|
|
oerr = bs.processStatus(req, res)
|
|
|
|
if oerr != nil {
|
2019-11-10 23:06:06 +00:00
|
|
|
log.Warnf("BlockSync peer %s response was an error: %s", p.String(), oerr)
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, xerrors.Errorf("GetBlocks failed with all peers: %w", oerr)
|
|
|
|
}
|
|
|
|
|
2019-12-16 19:22:56 +00:00
|
|
|
func (bs *BlockSync) GetFullTipSet(ctx context.Context, p peer.ID, tsk types.TipSetKey) (*store.FullTipSet, error) {
|
2019-11-10 19:33:08 +00:00
|
|
|
// TODO: round robin through these peers on error
|
|
|
|
|
|
|
|
req := &BlockSyncRequest{
|
2019-12-16 19:22:56 +00:00
|
|
|
Start: tsk.Cids(),
|
2019-11-10 19:33:08 +00:00
|
|
|
RequestLength: 1,
|
|
|
|
Options: BSOptBlocks | BSOptMessages,
|
|
|
|
}
|
|
|
|
|
|
|
|
res, err := bs.sendRequestToPeer(ctx, p, req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
switch res.Status {
|
|
|
|
case 0: // Success
|
|
|
|
if len(res.Chain) == 0 {
|
|
|
|
return nil, fmt.Errorf("got zero length chain response")
|
|
|
|
}
|
|
|
|
bts := res.Chain[0]
|
|
|
|
|
|
|
|
return bstsToFullTipSet(bts)
|
|
|
|
case 101: // Partial Response
|
2020-04-01 18:35:09 +00:00
|
|
|
return nil, xerrors.Errorf("partial responses are not handled for single tipset fetching")
|
2019-11-10 19:33:08 +00:00
|
|
|
case 201: // req.Start not found
|
|
|
|
return nil, fmt.Errorf("not found")
|
|
|
|
case 202: // Go Away
|
|
|
|
return nil, xerrors.Errorf("received 'go away' response peer")
|
|
|
|
case 203: // Internal Error
|
|
|
|
return nil, fmt.Errorf("block sync peer errored: %q", res.Message)
|
|
|
|
case 204: // Invalid Request
|
|
|
|
return nil, fmt.Errorf("block sync request invalid: %q", res.Message)
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("unrecognized response code")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-08 15:02:38 +00:00
|
|
|
func shufflePrefix(peers []peer.ID) {
|
|
|
|
pref := 5
|
|
|
|
if len(peers) < pref {
|
|
|
|
pref = len(peers)
|
|
|
|
}
|
|
|
|
|
|
|
|
buf := make([]peer.ID, pref)
|
|
|
|
perm := rand.Perm(pref)
|
|
|
|
for i, v := range perm {
|
|
|
|
buf[i] = peers[v]
|
|
|
|
}
|
|
|
|
|
|
|
|
copy(peers, buf)
|
|
|
|
}
|
|
|
|
|
2019-11-10 19:33:08 +00:00
|
|
|
func (bs *BlockSync) GetChainMessages(ctx context.Context, h *types.TipSet, count uint64) ([]*BSTipSet, error) {
|
|
|
|
ctx, span := trace.StartSpan(ctx, "GetChainMessages")
|
|
|
|
defer span.End()
|
|
|
|
|
|
|
|
peers := bs.getPeers()
|
2019-12-08 15:02:38 +00:00
|
|
|
// randomize the first few peers so we don't always pick the same peer
|
|
|
|
shufflePrefix(peers)
|
2019-11-10 19:33:08 +00:00
|
|
|
|
|
|
|
req := &BlockSyncRequest{
|
|
|
|
Start: h.Cids(),
|
|
|
|
RequestLength: count,
|
2020-04-01 18:35:09 +00:00
|
|
|
Options: BSOptMessages,
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
2019-12-08 16:24:51 +00:00
|
|
|
start := time.Now()
|
|
|
|
|
2019-12-08 15:02:38 +00:00
|
|
|
for _, p := range peers {
|
|
|
|
res, rerr := bs.sendRequestToPeer(ctx, p, req)
|
2019-12-01 04:10:23 +00:00
|
|
|
if rerr != nil {
|
|
|
|
err = rerr
|
2019-12-08 15:02:38 +00:00
|
|
|
log.Warnf("BlockSync request failed for peer %s: %s", p.String(), err)
|
2019-11-10 19:33:08 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-01-23 22:24:52 +00:00
|
|
|
if res.Status == StatusOK {
|
2019-12-08 16:24:51 +00:00
|
|
|
bs.syncPeers.logGlobalSuccess(time.Since(start))
|
2019-11-10 19:33:08 +00:00
|
|
|
return res.Chain, nil
|
|
|
|
}
|
2019-12-08 16:24:51 +00:00
|
|
|
|
2020-01-23 22:24:52 +00:00
|
|
|
if res.Status == StatusPartial {
|
2020-04-01 18:35:09 +00:00
|
|
|
// TODO: track partial response sizes to ensure we don't overrequest too often
|
|
|
|
return res.Chain, nil
|
2020-01-23 22:24:52 +00:00
|
|
|
}
|
|
|
|
|
2019-11-10 19:33:08 +00:00
|
|
|
err = bs.processStatus(req, res)
|
|
|
|
if err != nil {
|
2019-12-08 15:02:38 +00:00
|
|
|
log.Warnf("BlockSync peer %s response was an error: %s", p.String(), err)
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-01 04:10:23 +00:00
|
|
|
if err == nil {
|
|
|
|
return nil, xerrors.Errorf("GetChainMessages failed, no peers connected")
|
|
|
|
}
|
|
|
|
|
2019-11-10 19:33:08 +00:00
|
|
|
// TODO: What if we have no peers (and err is nil)?
|
|
|
|
return nil, xerrors.Errorf("GetChainMessages failed with all peers(%d): %w", len(peers), err)
|
|
|
|
}
|
|
|
|
|
2019-12-08 16:24:51 +00:00
|
|
|
func (bs *BlockSync) sendRequestToPeer(ctx context.Context, p peer.ID, req *BlockSyncRequest) (_ *BlockSyncResponse, err error) {
|
2019-11-10 19:33:08 +00:00
|
|
|
ctx, span := trace.StartSpan(ctx, "sendRequestToPeer")
|
|
|
|
defer span.End()
|
2019-12-08 16:24:51 +00:00
|
|
|
|
|
|
|
defer func() {
|
|
|
|
if err != nil {
|
|
|
|
if span.IsRecordingEvents() {
|
|
|
|
span.SetStatus(trace.Status{
|
|
|
|
Code: 5,
|
|
|
|
Message: err.Error(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2019-11-10 19:33:08 +00:00
|
|
|
if span.IsRecordingEvents() {
|
|
|
|
span.AddAttributes(
|
|
|
|
trace.StringAttribute("peer", p.Pretty()),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2020-03-19 04:13:04 +00:00
|
|
|
gsproto := string(gsnet.ProtocolGraphsync)
|
2020-03-23 20:46:15 +00:00
|
|
|
supp, err := bs.host.Peerstore().SupportsProtocols(p, BlockSyncProtocolID, gsproto)
|
2020-03-19 04:13:04 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, xerrors.Errorf("failed to get protocols for peer: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(supp) == 0 {
|
|
|
|
return nil, xerrors.Errorf("peer %s supports no known sync protocols", p)
|
|
|
|
}
|
|
|
|
|
|
|
|
switch supp[0] {
|
|
|
|
case BlockSyncProtocolID:
|
|
|
|
res, err := bs.fetchBlocksBlockSync(ctx, p, req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, xerrors.Errorf("blocksync req failed: %w", err)
|
|
|
|
}
|
|
|
|
return res, nil
|
|
|
|
case gsproto:
|
|
|
|
res, err := bs.fetchBlocksGraphSync(ctx, p, req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, xerrors.Errorf("graphsync req failed: %w", err)
|
|
|
|
}
|
|
|
|
return res, nil
|
|
|
|
default:
|
|
|
|
return nil, xerrors.Errorf("peerstore somehow returned unexpected protocols: %v", supp)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
func (bs *BlockSync) fetchBlocksBlockSync(ctx context.Context, p peer.ID, req *BlockSyncRequest) (*BlockSyncResponse, error) {
|
|
|
|
ctx, span := trace.StartSpan(ctx, "blockSyncFetch")
|
|
|
|
defer span.End()
|
|
|
|
|
|
|
|
start := time.Now()
|
2019-11-10 19:33:08 +00:00
|
|
|
s, err := bs.host.NewStream(inet.WithNoDial(ctx, "should already have connection"), p, BlockSyncProtocolID)
|
|
|
|
if err != nil {
|
|
|
|
bs.RemovePeer(p)
|
2019-11-10 23:06:06 +00:00
|
|
|
return nil, xerrors.Errorf("failed to open stream to peer: %w", err)
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
2020-05-27 20:53:20 +00:00
|
|
|
_ = s.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
2019-11-10 19:33:08 +00:00
|
|
|
|
|
|
|
if err := cborutil.WriteCborRPC(s, req); err != nil {
|
2020-05-27 20:53:20 +00:00
|
|
|
_ = s.SetWriteDeadline(time.Time{})
|
2019-12-08 16:24:51 +00:00
|
|
|
bs.syncPeers.logFailure(p, time.Since(start))
|
2019-11-10 19:33:08 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2020-05-27 20:53:20 +00:00
|
|
|
_ = s.SetWriteDeadline(time.Time{})
|
2019-11-10 19:33:08 +00:00
|
|
|
|
|
|
|
var res BlockSyncResponse
|
2020-01-22 23:57:42 +00:00
|
|
|
r := incrt.New(s, 50<<10, 5*time.Second)
|
|
|
|
if err := cborutil.ReadCborRPC(bufio.NewReader(r), &res); err != nil {
|
2019-12-08 16:24:51 +00:00
|
|
|
bs.syncPeers.logFailure(p, time.Since(start))
|
2019-11-10 19:33:08 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-11-13 06:44:29 +00:00
|
|
|
if span.IsRecordingEvents() {
|
|
|
|
span.AddAttributes(
|
|
|
|
trace.Int64Attribute("resp_status", int64(res.Status)),
|
|
|
|
trace.StringAttribute("msg", res.Message),
|
|
|
|
trace.Int64Attribute("chain_len", int64(len(res.Chain))),
|
|
|
|
)
|
|
|
|
}
|
2019-12-08 15:02:38 +00:00
|
|
|
|
|
|
|
bs.syncPeers.logSuccess(p, time.Since(start))
|
2019-11-10 19:33:08 +00:00
|
|
|
return &res, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (bs *BlockSync) processBlocksResponse(req *BlockSyncRequest, res *BlockSyncResponse) ([]*types.TipSet, error) {
|
2019-12-17 06:15:06 +00:00
|
|
|
if len(res.Chain) == 0 {
|
|
|
|
return nil, xerrors.Errorf("got no blocks in successful blocksync response")
|
|
|
|
}
|
|
|
|
|
2019-11-10 19:33:08 +00:00
|
|
|
cur, err := types.NewTipSet(res.Chain[0].Blocks)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
out := []*types.TipSet{cur}
|
|
|
|
for bi := 1; bi < len(res.Chain); bi++ {
|
|
|
|
next := res.Chain[bi].Blocks
|
|
|
|
nts, err := types.NewTipSet(next)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-12-16 19:22:56 +00:00
|
|
|
if !types.CidArrsEqual(cur.Parents().Cids(), nts.Cids()) {
|
2019-11-10 19:33:08 +00:00
|
|
|
return nil, fmt.Errorf("parents of tipset[%d] were not tipset[%d]", bi-1, bi)
|
|
|
|
}
|
|
|
|
|
|
|
|
out = append(out, nts)
|
|
|
|
cur = nts
|
|
|
|
}
|
|
|
|
return out, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (bs *BlockSync) GetBlock(ctx context.Context, c cid.Cid) (*types.BlockHeader, error) {
|
|
|
|
sb, err := bs.bserv.GetBlock(ctx, c)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return types.DecodeBlock(sb.RawData())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (bs *BlockSync) AddPeer(p peer.ID) {
|
|
|
|
bs.syncPeers.addPeer(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (bs *BlockSync) RemovePeer(p peer.ID) {
|
|
|
|
bs.syncPeers.removePeer(p)
|
|
|
|
}
|
|
|
|
|
2020-06-23 21:51:25 +00:00
|
|
|
// getPeers returns a preference-sorted set of peers to query.
|
2019-11-10 19:33:08 +00:00
|
|
|
func (bs *BlockSync) getPeers() []peer.ID {
|
|
|
|
return bs.syncPeers.prefSortedPeers()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (bs *BlockSync) FetchMessagesByCids(ctx context.Context, cids []cid.Cid) ([]*types.Message, error) {
|
|
|
|
out := make([]*types.Message, len(cids))
|
|
|
|
|
|
|
|
err := bs.fetchCids(ctx, cids, func(i int, b blocks.Block) error {
|
|
|
|
msg, err := types.DecodeMessage(b.RawData())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if out[i] != nil {
|
|
|
|
return fmt.Errorf("received duplicate message")
|
|
|
|
}
|
|
|
|
|
|
|
|
out[i] = msg
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return out, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (bs *BlockSync) FetchSignedMessagesByCids(ctx context.Context, cids []cid.Cid) ([]*types.SignedMessage, error) {
|
|
|
|
out := make([]*types.SignedMessage, len(cids))
|
|
|
|
|
|
|
|
err := bs.fetchCids(ctx, cids, func(i int, b blocks.Block) error {
|
|
|
|
smsg, err := types.DecodeSignedMessage(b.RawData())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if out[i] != nil {
|
|
|
|
return fmt.Errorf("received duplicate message")
|
|
|
|
}
|
|
|
|
|
|
|
|
out[i] = smsg
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return out, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (bs *BlockSync) fetchCids(ctx context.Context, cids []cid.Cid, cb func(int, blocks.Block) error) error {
|
|
|
|
resp := bs.bserv.GetBlocks(context.TODO(), cids)
|
|
|
|
|
|
|
|
m := make(map[cid.Cid]int)
|
|
|
|
for i, c := range cids {
|
|
|
|
m[c] = i
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := 0; i < len(cids); i++ {
|
|
|
|
select {
|
|
|
|
case v, ok := <-resp:
|
|
|
|
if !ok {
|
|
|
|
if i == len(cids)-1 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
return fmt.Errorf("failed to fetch all messages")
|
|
|
|
}
|
|
|
|
|
|
|
|
ix, ok := m[v.Cid()]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("received message we didnt ask for")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := cb(ix, v); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type peerStats struct {
|
2019-12-08 15:02:38 +00:00
|
|
|
successes int
|
|
|
|
failures int
|
|
|
|
firstSeen time.Time
|
|
|
|
averageTime time.Duration
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type bsPeerTracker struct {
|
2019-12-08 16:24:51 +00:00
|
|
|
lk sync.Mutex
|
|
|
|
|
|
|
|
peers map[peer.ID]*peerStats
|
|
|
|
avgGlobalTime time.Duration
|
2019-12-10 15:02:01 +00:00
|
|
|
|
|
|
|
pmgr *peermgr.PeerMgr
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
|
|
|
|
2019-12-10 15:02:01 +00:00
|
|
|
func newPeerTracker(pmgr *peermgr.PeerMgr) *bsPeerTracker {
|
2019-11-10 19:33:08 +00:00
|
|
|
return &bsPeerTracker{
|
|
|
|
peers: make(map[peer.ID]*peerStats),
|
2019-12-10 15:02:01 +00:00
|
|
|
pmgr: pmgr,
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
|
|
|
}
|
2019-12-08 16:24:51 +00:00
|
|
|
|
2019-11-10 19:33:08 +00:00
|
|
|
func (bpt *bsPeerTracker) addPeer(p peer.ID) {
|
|
|
|
bpt.lk.Lock()
|
|
|
|
defer bpt.lk.Unlock()
|
|
|
|
if _, ok := bpt.peers[p]; ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
bpt.peers[p] = &peerStats{
|
|
|
|
firstSeen: time.Now(),
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2019-12-08 19:32:34 +00:00
|
|
|
const (
|
|
|
|
// newPeerMul is how much better than average is the new peer assumed to be
|
|
|
|
// less than one to encourouge trying new peers
|
|
|
|
newPeerMul = 0.9
|
|
|
|
)
|
|
|
|
|
2019-11-10 19:33:08 +00:00
|
|
|
func (bpt *bsPeerTracker) prefSortedPeers() []peer.ID {
|
|
|
|
// TODO: this could probably be cached, but as long as its not too many peers, fine for now
|
|
|
|
bpt.lk.Lock()
|
|
|
|
defer bpt.lk.Unlock()
|
|
|
|
out := make([]peer.ID, 0, len(bpt.peers))
|
|
|
|
for p := range bpt.peers {
|
|
|
|
out = append(out, p)
|
|
|
|
}
|
|
|
|
|
2019-12-08 15:02:38 +00:00
|
|
|
// sort by 'expected cost' of requesting data from that peer
|
|
|
|
// additionally handle edge cases where not enough data is available
|
2019-11-10 19:33:08 +00:00
|
|
|
sort.Slice(out, func(i, j int) bool {
|
|
|
|
pi := bpt.peers[out[i]]
|
|
|
|
pj := bpt.peers[out[j]]
|
2019-12-08 15:02:38 +00:00
|
|
|
|
2019-12-08 16:24:51 +00:00
|
|
|
var costI, costJ float64
|
|
|
|
|
2019-12-10 15:02:01 +00:00
|
|
|
getPeerInitLat := func(p peer.ID) float64 {
|
|
|
|
var res float64
|
|
|
|
if bpt.pmgr != nil {
|
2020-01-19 05:48:15 +00:00
|
|
|
if lat, ok := bpt.pmgr.GetPeerLatency(p); ok {
|
2019-12-10 15:02:01 +00:00
|
|
|
res = float64(lat)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if res == 0 {
|
|
|
|
res = float64(bpt.avgGlobalTime)
|
|
|
|
}
|
|
|
|
return res * newPeerMul
|
|
|
|
}
|
|
|
|
|
2019-12-08 16:24:51 +00:00
|
|
|
if pi.successes+pi.failures > 0 {
|
2019-12-08 15:02:38 +00:00
|
|
|
failRateI := float64(pi.failures) / float64(pi.failures+pi.successes)
|
2019-12-08 16:24:51 +00:00
|
|
|
costI = float64(pi.averageTime) + failRateI*float64(bpt.avgGlobalTime)
|
|
|
|
} else {
|
2019-12-10 15:02:01 +00:00
|
|
|
costI = getPeerInitLat(out[i])
|
2019-12-08 16:24:51 +00:00
|
|
|
}
|
2019-12-08 15:02:38 +00:00
|
|
|
|
2019-12-08 16:24:51 +00:00
|
|
|
if pj.successes+pj.failures > 0 {
|
2019-12-08 15:02:38 +00:00
|
|
|
failRateJ := float64(pj.failures) / float64(pj.failures+pj.successes)
|
2019-12-08 16:24:51 +00:00
|
|
|
costJ = float64(pj.averageTime) + failRateJ*float64(bpt.avgGlobalTime)
|
|
|
|
} else {
|
2020-01-19 05:48:15 +00:00
|
|
|
costJ = getPeerInitLat(out[j])
|
2019-12-08 15:02:38 +00:00
|
|
|
}
|
|
|
|
|
2019-12-08 16:24:51 +00:00
|
|
|
return costI < costJ
|
2019-11-10 19:33:08 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
return out
|
|
|
|
}
|
|
|
|
|
2019-12-08 19:32:34 +00:00
|
|
|
const (
|
|
|
|
// xInvAlpha = (N+1)/2
|
|
|
|
|
|
|
|
localInvAlpha = 5 // 86% of the value is the last 9
|
|
|
|
globalInvAlpha = 20 // 86% of the value is the last 39
|
|
|
|
)
|
|
|
|
|
2019-12-08 16:24:51 +00:00
|
|
|
func (bpt *bsPeerTracker) logGlobalSuccess(dur time.Duration) {
|
|
|
|
bpt.lk.Lock()
|
|
|
|
defer bpt.lk.Unlock()
|
|
|
|
|
2019-12-08 19:32:34 +00:00
|
|
|
if bpt.avgGlobalTime == 0 {
|
|
|
|
bpt.avgGlobalTime = dur
|
|
|
|
return
|
|
|
|
}
|
|
|
|
delta := (dur - bpt.avgGlobalTime) / globalInvAlpha
|
2019-12-08 16:24:51 +00:00
|
|
|
bpt.avgGlobalTime += delta
|
|
|
|
}
|
|
|
|
|
2019-12-08 19:32:34 +00:00
|
|
|
func logTime(pi *peerStats, dur time.Duration) {
|
|
|
|
if pi.averageTime == 0 {
|
|
|
|
pi.averageTime = dur
|
|
|
|
return
|
|
|
|
}
|
|
|
|
delta := (dur - pi.averageTime) / localInvAlpha
|
|
|
|
pi.averageTime += delta
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2019-12-08 15:02:38 +00:00
|
|
|
func (bpt *bsPeerTracker) logSuccess(p peer.ID, dur time.Duration) {
|
2019-11-10 19:33:08 +00:00
|
|
|
bpt.lk.Lock()
|
|
|
|
defer bpt.lk.Unlock()
|
2019-12-08 16:24:51 +00:00
|
|
|
|
2020-06-02 14:29:39 +00:00
|
|
|
var pi *peerStats
|
|
|
|
var ok bool
|
|
|
|
if pi, ok = bpt.peers[p]; !ok {
|
2019-12-08 19:32:34 +00:00
|
|
|
log.Warnw("log success called on peer not in tracker", "peerid", p.String())
|
2019-11-10 19:33:08 +00:00
|
|
|
return
|
|
|
|
}
|
2020-06-02 14:29:39 +00:00
|
|
|
|
|
|
|
pi.successes++
|
|
|
|
logTime(pi, dur)
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
|
|
|
|
2019-12-08 16:24:51 +00:00
|
|
|
func (bpt *bsPeerTracker) logFailure(p peer.ID, dur time.Duration) {
|
2019-11-10 19:33:08 +00:00
|
|
|
bpt.lk.Lock()
|
|
|
|
defer bpt.lk.Unlock()
|
2020-06-02 14:29:39 +00:00
|
|
|
|
|
|
|
var pi *peerStats
|
|
|
|
var ok bool
|
|
|
|
if pi, ok = bpt.peers[p]; !ok {
|
2019-12-08 19:32:34 +00:00
|
|
|
log.Warn("log failure called on peer not in tracker", "peerid", p.String())
|
2019-11-10 19:33:08 +00:00
|
|
|
return
|
|
|
|
}
|
2020-06-02 14:29:39 +00:00
|
|
|
|
|
|
|
pi.failures++
|
|
|
|
logTime(pi, dur)
|
2019-11-10 19:33:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (bpt *bsPeerTracker) removePeer(p peer.ID) {
|
|
|
|
bpt.lk.Lock()
|
|
|
|
defer bpt.lk.Unlock()
|
|
|
|
delete(bpt.peers, p)
|
|
|
|
}
|