package v2peer import ( "bytes" "errors" "fmt" "time" "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/wire/v2" ) // ErrNotFound is a peer saying it does not have a block its headers claim it // has. var ErrNotFound = errors.New("v2peer: the peer does not have the block") // Block asks for one block and returns its serialized form: getdata in, block // out, with everything the peer says in between handled here so the caller // gets the answer or the reason and nothing else. // // The block arrives as btcd's MsgBlock in a witness encoding; what a store // wants is the bytes, so the message is serialized back with its witness. The // hash the caller asked for is checked by the caller against the bytes, which // is where it belongs. func (p *Peer) Block(hash chainhash.Hash, timeout time.Duration) ([]byte, error) { // The caller may be anywhere in the process, so a hash of this project's // type is converted here rather than at every call site. return p.BlockFor(chainhash.Hash(hash), timeout) } // BlockFor is Block with btcd's hash type, which is what an address with a // wire order carries. func (p *Peer) BlockFor(hash chainhash.Hash, timeout time.Duration) ([]byte, error) { gd := &wire.MsgGetData{InvList: []*wire.InvVect{wire.NewInvVect(wire.InvTypeWitnessBlock, &hash)}} if err := p.Write(gd); err != nil { return nil, err } timer := time.NewTimer(timeout) defer timer.Stop() for { select { case <-timer.C: return nil, fmt.Errorf("v2peer: no answer for %s within %s", hash, timeout) case <-p.done: return nil, fmt.Errorf("v2peer: the connection ended: %w", p.Err()) case m, ok := <-p.recv: if !ok { return nil, fmt.Errorf("v2peer: the connection ended: %w", p.Err()) } switch msg := m.Message.(type) { case *wire.MsgBlock: var buf bytes.Buffer if err := msg.Serialize(&buf); err != nil { return nil, err } return buf.Bytes(), nil case *wire.MsgNotFound: for _, inv := range msg.InvList { if inv.Type == wire.InvTypeWitnessBlock || inv.Type == wire.InvTypeBlock { return nil, ErrNotFound } } } } } }