1 package v2peer
2 3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "time"
8 9 "github.com/btcsuite/btcd/chainhash/v2"
10 "github.com/btcsuite/btcd/wire/v2"
11 )
12 13 // ErrNotFound is a peer saying it does not have a block its headers claim it
14 // has.
15 var ErrNotFound = errors.New("v2peer: the peer does not have the block")
16 17 // Block asks for one block and returns its serialized form: getdata in, block
18 // out, with everything the peer says in between handled here so the caller
19 // gets the answer or the reason and nothing else.
20 //
21 // The block arrives as btcd's MsgBlock in a witness encoding; what a store
22 // wants is the bytes, so the message is serialized back with its witness. The
23 // hash the caller asked for is checked by the caller against the bytes, which
24 // is where it belongs.
25 func (p *Peer) Block(hash chainhash.Hash, timeout time.Duration) ([]byte, error) {
26 // The caller may be anywhere in the process, so a hash of this project's
27 // type is converted here rather than at every call site.
28 return p.BlockFor(chainhash.Hash(hash), timeout)
29 }
30 31 // BlockFor is Block with btcd's hash type, which is what an address with a
32 // wire order carries.
33 func (p *Peer) BlockFor(hash chainhash.Hash, timeout time.Duration) ([]byte, error) {
34 gd := &wire.MsgGetData{InvList: []*wire.InvVect{wire.NewInvVect(wire.InvTypeWitnessBlock, &hash)}}
35 if err := p.Write(gd); err != nil {
36 return nil, err
37 }
38 timer := time.NewTimer(timeout)
39 defer timer.Stop()
40 for {
41 select {
42 case <-timer.C:
43 return nil, fmt.Errorf("v2peer: no answer for %s within %s", hash, timeout)
44 case <-p.done:
45 return nil, fmt.Errorf("v2peer: the connection ended: %w", p.Err())
46 case m, ok := <-p.recv:
47 if !ok {
48 return nil, fmt.Errorf("v2peer: the connection ended: %w", p.Err())
49 }
50 switch msg := m.Message.(type) {
51 case *wire.MsgBlock:
52 var buf bytes.Buffer
53 if err := msg.Serialize(&buf); err != nil {
54 return nil, err
55 }
56 return buf.Bytes(), nil
57 case *wire.MsgNotFound:
58 for _, inv := range msg.InvList {
59 if inv.Type == wire.InvTypeWitnessBlock || inv.Type == wire.InvTypeBlock {
60 return nil, ErrNotFound
61 }
62 }
63 }
64 }
65 }
66 }
67