lotus/chain/sync.go

503 lines
12 KiB
Go
Raw Normal View History

2019-07-05 14:29:17 +00:00
package chain
import (
"context"
"fmt"
"sync"
2019-07-26 18:16:57 +00:00
"golang.org/x/xerrors"
2019-07-12 23:52:25 +00:00
"github.com/filecoin-project/go-lotus/chain/actors"
2019-07-26 04:54:22 +00:00
"github.com/filecoin-project/go-lotus/chain/store"
"github.com/filecoin-project/go-lotus/chain/types"
2019-07-26 04:54:22 +00:00
"github.com/filecoin-project/go-lotus/chain/vm"
2019-07-08 12:51:45 +00:00
2019-07-05 14:29:17 +00:00
"github.com/ipfs/go-cid"
dstore "github.com/ipfs/go-datastore"
"github.com/ipfs/go-hamt-ipld"
bstore "github.com/ipfs/go-ipfs-blockstore"
2019-07-26 04:54:22 +00:00
logging "github.com/ipfs/go-log"
2019-07-30 16:39:07 +00:00
"github.com/libp2p/go-libp2p-core/peer"
2019-07-05 14:29:17 +00:00
"github.com/pkg/errors"
"github.com/whyrusleeping/sharray"
)
2019-07-26 04:54:22 +00:00
const ForkLengthThreshold = 20
var log = logging.Logger("chain")
2019-07-05 14:29:17 +00:00
type Syncer struct {
// The heaviest known tipset in the network.
2019-07-26 04:54:22 +00:00
head *types.TipSet
2019-07-05 14:29:17 +00:00
// The interface for accessing and putting tipsets into local storage
2019-07-26 04:54:22 +00:00
store *store.ChainStore
2019-07-05 14:29:17 +00:00
2019-07-05 14:46:21 +00:00
// The known Genesis tipset
2019-07-26 04:54:22 +00:00
Genesis *types.TipSet
2019-07-05 14:29:17 +00:00
syncLock sync.Mutex
// TipSets known to be invalid
bad BadTipSetCache
// handle to the block sync service
2019-07-08 14:07:09 +00:00
Bsync *BlockSync
2019-07-05 14:29:17 +00:00
2019-07-11 02:36:43 +00:00
self peer.ID
2019-07-05 14:29:17 +00:00
// peer heads
// Note: clear cache on disconnects
2019-07-26 04:54:22 +00:00
peerHeads map[peer.ID]*types.TipSet
2019-07-05 14:29:17 +00:00
peerHeadsLk sync.Mutex
}
2019-07-26 04:54:22 +00:00
func NewSyncer(cs *store.ChainStore, bsync *BlockSync, self peer.ID) (*Syncer, error) {
2019-07-05 14:29:17 +00:00
gen, err := cs.GetGenesis()
if err != nil {
return nil, err
}
2019-07-26 04:54:22 +00:00
gent, err := types.NewTipSet([]*types.BlockHeader{gen})
2019-07-05 14:29:17 +00:00
if err != nil {
return nil, err
}
return &Syncer{
2019-07-05 14:46:21 +00:00
Genesis: gent,
2019-07-08 14:07:09 +00:00
Bsync: bsync,
2019-07-26 04:54:22 +00:00
peerHeads: make(map[peer.ID]*types.TipSet),
2019-07-05 14:29:17 +00:00
head: cs.GetHeaviestTipSet(),
store: cs,
2019-07-11 02:36:43 +00:00
self: self,
2019-07-05 14:29:17 +00:00
}, nil
}
type BadTipSetCache struct {
badBlocks map[cid.Cid]struct{}
}
const BootstrapPeerThreshold = 1
// InformNewHead informs the syncer about a new potential tipset
// This should be called when connecting to new peers, and additionally
// when receiving new blocks from the network
2019-07-26 04:54:22 +00:00
func (syncer *Syncer) InformNewHead(from peer.ID, fts *store.FullTipSet) {
2019-07-05 14:29:17 +00:00
if fts == nil {
panic("bad")
}
2019-07-11 02:36:43 +00:00
if from == syncer.self {
// TODO: this is kindof a hack...
log.Infof("got block from ourselves")
2019-07-30 16:39:07 +00:00
if err := syncer.Sync(fts); err != nil {
2019-07-11 02:36:43 +00:00
log.Errorf("failed to sync our own block: %s", err)
}
return
}
2019-07-05 14:29:17 +00:00
syncer.peerHeadsLk.Lock()
syncer.peerHeads[from] = fts.TipSet()
syncer.peerHeadsLk.Unlock()
2019-07-08 14:07:09 +00:00
syncer.Bsync.AddPeer(from)
2019-07-05 14:29:17 +00:00
go func() {
2019-07-30 16:39:07 +00:00
if err := syncer.Sync(fts); err != nil {
2019-07-26 18:16:57 +00:00
log.Errorf("sync error: %s", err)
2019-07-05 14:29:17 +00:00
}
}()
}
func (syncer *Syncer) InformNewBlock(from peer.ID, blk *types.FullBlock) {
2019-07-05 14:29:17 +00:00
// TODO: search for other blocks that could form a tipset with this block
// and then send that tipset to InformNewHead
2019-07-26 04:54:22 +00:00
fts := &store.FullTipSet{Blocks: []*types.FullBlock{blk}}
2019-07-05 14:29:17 +00:00
syncer.InformNewHead(from, fts)
}
2019-07-26 04:54:22 +00:00
func reverse(tips []*types.TipSet) []*types.TipSet {
out := make([]*types.TipSet, len(tips))
2019-07-05 14:29:17 +00:00
for i := 0; i < len(tips); i++ {
out[i] = tips[len(tips)-(i+1)]
}
return out
}
func copyBlockstore(from, to bstore.Blockstore) error {
cids, err := from.AllKeysChan(context.TODO())
if err != nil {
return err
}
for c := range cids {
b, err := from.Get(c)
if err != nil {
return err
}
if err := to.Put(b); err != nil {
return err
}
}
return nil
}
2019-07-26 04:54:22 +00:00
func zipTipSetAndMessages(cst *hamt.CborIpldStore, ts *types.TipSet, messages []*types.SignedMessage, msgincl [][]int) (*store.FullTipSet, error) {
2019-07-05 14:29:17 +00:00
if len(ts.Blocks()) != len(msgincl) {
return nil, fmt.Errorf("msgincl length didnt match tipset size")
}
2019-07-26 04:54:22 +00:00
fts := &store.FullTipSet{}
2019-07-05 14:29:17 +00:00
for bi, b := range ts.Blocks() {
var msgs []*types.SignedMessage
2019-07-05 14:29:17 +00:00
var msgCids []interface{}
for _, m := range msgincl[bi] {
msgs = append(msgs, messages[m])
msgCids = append(msgCids, messages[m].Cid())
}
mroot, err := sharray.Build(context.TODO(), 4, msgCids, cst)
if err != nil {
return nil, err
}
if b.Messages != mroot {
return nil, fmt.Errorf("messages didnt match message root in header")
}
fb := &types.FullBlock{
2019-07-05 14:29:17 +00:00
Header: b,
Messages: msgs,
}
fts.Blocks = append(fts.Blocks, fb)
}
return fts, nil
}
2019-07-26 04:54:22 +00:00
func (syncer *Syncer) selectHead(heads map[peer.ID]*types.TipSet) (*types.TipSet, error) {
var headsArr []*types.TipSet
2019-07-05 14:29:17 +00:00
for _, ts := range heads {
headsArr = append(headsArr, ts)
}
sel := headsArr[0]
for i := 1; i < len(headsArr); i++ {
cur := headsArr[i]
yes, err := syncer.store.IsAncestorOf(cur, sel)
if err != nil {
return nil, err
}
if yes {
continue
}
yes, err = syncer.store.IsAncestorOf(sel, cur)
if err != nil {
return nil, err
}
if yes {
sel = cur
continue
}
nca, err := syncer.store.NearestCommonAncestor(cur, sel)
if err != nil {
return nil, err
}
if sel.Height()-nca.Height() > ForkLengthThreshold {
// TODO: handle this better than refusing to sync
return nil, fmt.Errorf("Conflict exists in heads set")
}
if syncer.store.Weight(cur) > syncer.store.Weight(sel) {
sel = cur
}
}
return sel, nil
}
2019-07-26 04:54:22 +00:00
func (syncer *Syncer) FetchTipSet(ctx context.Context, p peer.ID, cids []cid.Cid) (*store.FullTipSet, error) {
2019-07-05 14:29:17 +00:00
if fts, err := syncer.tryLoadFullTipSet(cids); err == nil {
return fts, nil
}
2019-07-08 14:07:09 +00:00
return syncer.Bsync.GetFullTipSet(ctx, p, cids)
2019-07-05 14:29:17 +00:00
}
2019-07-26 04:54:22 +00:00
func (syncer *Syncer) tryLoadFullTipSet(cids []cid.Cid) (*store.FullTipSet, error) {
2019-07-05 14:29:17 +00:00
ts, err := syncer.store.LoadTipSet(cids)
if err != nil {
return nil, err
}
2019-07-26 04:54:22 +00:00
fts := &store.FullTipSet{}
2019-07-05 14:29:17 +00:00
for _, b := range ts.Blocks() {
messages, err := syncer.store.MessagesForBlock(b)
if err != nil {
return nil, err
}
fb := &types.FullBlock{
2019-07-05 14:29:17 +00:00
Header: b,
Messages: messages,
}
fts.Blocks = append(fts.Blocks, fb)
}
return fts, nil
}
2019-07-30 16:39:07 +00:00
func (syncer *Syncer) Sync(maybeHead *store.FullTipSet) error {
2019-07-26 18:16:57 +00:00
syncer.syncLock.Lock()
defer syncer.syncLock.Unlock()
2019-07-05 14:29:17 +00:00
ts := maybeHead.TipSet()
2019-07-05 14:46:21 +00:00
if syncer.Genesis.Equals(ts) {
2019-07-05 14:29:17 +00:00
return nil
}
2019-07-31 07:13:49 +00:00
if err := syncer.collectChain(maybeHead); err != nil {
2019-07-05 14:29:17 +00:00
return err
}
if err := syncer.store.PutTipSet(maybeHead); err != nil {
return errors.Wrap(err, "failed to put synced tipset to chainstore")
}
2019-07-31 07:13:49 +00:00
if syncer.store.Weight(maybeHead.TipSet()) > syncer.store.Weight(syncer.head) {
fmt.Println("Accepted new head: ", maybeHead.Cids())
syncer.head = maybeHead.TipSet()
2019-07-05 14:29:17 +00:00
}
return nil
}
func (syncer *Syncer) ValidateTipSet(ctx context.Context, fts *store.FullTipSet) error {
2019-07-05 14:29:17 +00:00
ts := fts.TipSet()
2019-07-05 14:46:21 +00:00
if ts.Equals(syncer.Genesis) {
2019-07-05 14:29:17 +00:00
return nil
}
for _, b := range fts.Blocks {
if err := syncer.ValidateBlock(ctx, b); err != nil {
2019-07-05 14:29:17 +00:00
return err
}
}
return nil
}
func (syncer *Syncer) ValidateBlock(ctx context.Context, b *types.FullBlock) error {
2019-07-05 14:29:17 +00:00
h := b.Header
stateroot, err := syncer.store.TipSetState(h.Parents)
if err != nil {
log.Error("get tipsetstate failed: ", h.Height, h.Parents, err)
return err
}
baseTs, err := syncer.store.LoadTipSet(b.Header.Parents)
if err != nil {
return err
}
2019-07-25 22:15:33 +00:00
vmi, err := vm.NewVM(stateroot, b.Header.Height, b.Header.Miner, syncer.store)
2019-07-05 14:29:17 +00:00
if err != nil {
return err
}
2019-07-25 22:15:33 +00:00
if err := vmi.TransferFunds(actors.NetworkAddress, b.Header.Miner, vm.MiningRewardForBlock(baseTs)); err != nil {
2019-07-05 14:29:17 +00:00
return err
}
var receipts []interface{}
for _, m := range b.Messages {
2019-07-25 22:15:33 +00:00
receipt, err := vmi.ApplyMessage(ctx, &m.Message)
2019-07-05 14:29:17 +00:00
if err != nil {
return err
}
receipts = append(receipts, receipt)
}
2019-07-26 04:54:22 +00:00
cst := hamt.CSTFromBstore(syncer.store.Blockstore())
2019-07-05 14:29:17 +00:00
recptRoot, err := sharray.Build(context.TODO(), 4, receipts, cst)
if err != nil {
return err
}
if recptRoot != b.Header.MessageReceipts {
return fmt.Errorf("receipts mismatched")
}
2019-07-25 22:15:33 +00:00
final, err := vmi.Flush(context.TODO())
2019-07-05 14:29:17 +00:00
if err != nil {
return err
}
if b.Header.StateRoot != final {
return fmt.Errorf("final state root does not match block")
}
return nil
}
2019-07-31 07:13:49 +00:00
func (syncer *Syncer) collectHeaders(from *types.TipSet, toHeight uint64) ([]*types.TipSet, error) {
blockSet := []*types.TipSet{from}
2019-07-05 14:29:17 +00:00
2019-07-31 07:13:49 +00:00
at := from.Parents()
2019-07-05 14:29:17 +00:00
2019-07-31 07:13:49 +00:00
// If, for some reason, we have a suffix of the chain locally, handle that here
for blockSet[len(blockSet)-1].Height() > toHeight {
log.Warn("syncing local: ", at)
ts, err := syncer.store.LoadTipSet(at)
if err != nil {
if err == bstore.ErrNotFound {
log.Info("tipset not found locally, starting sync: ", at)
break
}
log.Warn("loading local tipset: %s", err)
continue // TODO: verify
}
2019-07-26 18:16:57 +00:00
2019-07-31 07:13:49 +00:00
blockSet = append(blockSet, ts)
at = ts.Parents()
}
2019-07-31 07:13:49 +00:00
for blockSet[len(blockSet)-1].Height() > toHeight {
// NB: GetBlocks validates that the blocks are in-fact the ones we
// requested, and that they are correctly linked to eachother. It does
// not validate any state transitions
fmt.Println("Get blocks")
blks, err := syncer.Bsync.GetBlocks(context.TODO(), at, 10)
if err != nil {
// Most likely our peers aren't fully synced yet, but forwarded
// new block message (ideally we'd find better peers)
2019-07-26 18:16:57 +00:00
2019-07-31 07:13:49 +00:00
log.Error("failed to get blocks: ", err)
2019-07-26 18:16:57 +00:00
2019-07-31 07:13:49 +00:00
// This error will only be logged above,
return nil, xerrors.Errorf("failed to get blocks: %w", err)
}
2019-07-26 18:16:57 +00:00
2019-07-31 07:13:49 +00:00
for _, b := range blks {
blockSet = append(blockSet, b)
}
2019-07-26 18:16:57 +00:00
2019-07-31 07:13:49 +00:00
at = blks[len(blks)-1].Parents()
}
2019-07-31 07:13:49 +00:00
if toHeight == 0 {
// hacks. in the case that we request X blocks starting at height X+1, we
// won't get the Genesis block in the returned blockset. This hacks around it
if blockSet[len(blockSet)-1].Height() != 0 {
blockSet = append(blockSet, syncer.Genesis)
}
2019-07-31 07:13:49 +00:00
blockSet = reverse(blockSet)
2019-07-31 07:13:49 +00:00
genesis := blockSet[0]
if !genesis.Equals(syncer.Genesis) {
// TODO: handle this...
log.Errorf("We synced to the wrong chain! %s != %s", genesis, syncer.Genesis)
panic("We synced to the wrong chain")
}
2019-07-31 07:13:49 +00:00
}
2019-07-26 18:16:57 +00:00
2019-07-31 07:13:49 +00:00
return blockSet, nil
}
2019-07-26 18:16:57 +00:00
2019-07-31 07:13:49 +00:00
func (syncer *Syncer) syncMessagesAndCheckState(headers []*types.TipSet) error {
// Fetch all the messages for all the blocks in this chain
cur := headers[len(headers)-1]
2019-07-31 07:13:49 +00:00
windowSize := uint64(10)
for i := uint64(0); i <= cur.Height(); i += windowSize {
ds := dstore.NewMapDatastore()
bs := bstore.NewBlockstore(ds)
cst := hamt.CSTFromBstore(bs)
2019-07-26 18:16:57 +00:00
2019-07-31 07:13:49 +00:00
nextHeight := i + windowSize - 1
if nextHeight > cur.Height() {
nextHeight = cur.Height()
}
2019-07-31 07:13:49 +00:00
next := headers[nextHeight]
bstips, err := syncer.Bsync.GetChainMessages(context.TODO(), next, (nextHeight+1)-i)
if err != nil {
log.Errorf("failed to fetch messages: %s", err)
return xerrors.Errorf("message processing failed: %w", err)
}
2019-07-31 07:13:49 +00:00
for bsi := 0; bsi < len(bstips); bsi++ {
this := headers[i+uint64(bsi)]
bstip := bstips[len(bstips)-(bsi+1)]
fts, err := zipTipSetAndMessages(cst, this, bstip.Messages, bstip.MsgIncludes)
if err != nil {
2019-07-31 07:13:49 +00:00
log.Error("zipping failed: ", err, bsi, i)
log.Error("height: ", this.Height())
log.Error("bstips: ", bstips)
log.Error("next height: ", nextHeight)
return xerrors.Errorf("message processing failed: %w", err)
}
2019-07-26 18:16:57 +00:00
2019-07-31 07:13:49 +00:00
if err := syncer.ValidateTipSet(context.TODO(), fts); err != nil {
log.Errorf("failed to validate tipset: %s", err)
return xerrors.Errorf("message processing failed: %w", err)
}
2019-07-31 07:13:49 +00:00
}
2019-07-26 18:16:57 +00:00
2019-07-31 07:13:49 +00:00
for _, bst := range bstips {
for _, m := range bst.Messages {
switch m.Signature.Type {
case types.KTBLS:
//log.Infof("putting BLS message: %s", m.Cid())
if _, err := store.PutMessage(bs, &m.Message); err != nil {
log.Error("failed to persist messages: ", err)
2019-07-31 07:13:49 +00:00
return xerrors.Errorf("BLS message processing failed: %w", err)
2019-07-26 18:16:57 +00:00
}
2019-07-31 07:13:49 +00:00
case types.KTSecp256k1:
//log.Infof("putting secp256k1 message: %s", m.Cid())
if _, err := store.PutMessage(bs, m); err != nil {
log.Error("failed to persist messages: ", err)
return xerrors.Errorf("secp256k1 message processing failed: %w", err)
}
default:
return xerrors.Errorf("unknown signature type on message %s: %q", m.Cid(), m.Signature.TypeCode)
2019-07-26 18:16:57 +00:00
}
}
2019-07-31 07:13:49 +00:00
}
2019-07-31 07:13:49 +00:00
if err := copyBlockstore(bs, syncer.store.Blockstore()); err != nil {
return xerrors.Errorf("message processing failed: %w", err)
2019-07-05 14:29:17 +00:00
}
2019-07-31 07:13:49 +00:00
}
2019-07-05 14:29:17 +00:00
2019-07-31 07:13:49 +00:00
return nil
}
2019-07-05 14:29:17 +00:00
2019-07-31 07:13:49 +00:00
func (syncer *Syncer) collectChain(fts *store.FullTipSet) error {
curHeight := syncer.head.Height()
headers, err := syncer.collectHeaders(fts.TipSet(), curHeight)
if err != nil {
return err
}
for _, ts := range headers {
for _, b := range ts.Blocks() {
if err := syncer.store.PersistBlockHeader(b); err != nil {
return xerrors.Errorf("failed to persist synced blocks to the chainstore: %w", err)
}
}
2019-07-05 14:29:17 +00:00
}
2019-07-31 07:13:49 +00:00
if err := syncer.syncMessagesAndCheckState(headers); err != nil {
return err
}
return nil
2019-07-05 14:36:08 +00:00
}