Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 79 additions & 11 deletions chainreg/blake2b_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,11 @@ type ChainIdentityStatus struct {
ChainHash string `json:"chain_hash"`
ActivationHeight uint32 `json:"activation_height"`
ActivationHash string `json:"activation_hash,omitempty"`
NodeHeaders int32 `json:"node_headers,omitempty"`

// NodeHeaders is, while waiting, how far the node's active chain
// reaches: the block it would serve for the activation height. The
// name is kept for the wrappers that read it.
NodeHeaders int32 `json:"node_headers,omitempty"`

// ReducedData is the state of the chain's temporary block-size
// reduction (RDTS), read from the node's getdeploymentinfo once the
Expand All @@ -120,6 +124,12 @@ type ErrWrongChain struct {
// Unreachable is set when the node could not answer at all (it is
// restarting or warming up), which says nothing about its chain.
Unreachable bool

// Missing is set when the node answered but did not have the
// activation block or its header. On a node whose active chain is
// below the activation height (a reindex rebuilding it from genesis)
// that says nothing about its chain either; see verifyWaiting.
Missing bool
}

// Error implements the error interface.
Expand Down Expand Up @@ -312,7 +322,7 @@ func (c *chainIdentityChecker) verifyOnce(height uint32) (chainhash.Hash,
if err != nil {
return chainhash.Hash{}, &ErrWrongChain{Reason: fmt.Sprintf(
"the node cannot serve block %d: %v", height, err),
Unreachable: nodeUnreachable(err)}
Unreachable: nodeUnreachable(err), Missing: true}
}

hashParam, err := json.Marshal(nodeHash.String())
Expand All @@ -329,7 +339,8 @@ func (c *chainIdentityChecker) verifyOnce(height uint32) (chainhash.Hash,
if err != nil {
return chainhash.Hash{}, &ErrWrongChain{Reason: fmt.Sprintf(
"the node cannot serve the header of block %d: %v",
height, err), Unreachable: nodeUnreachable(err)}
height, err), Unreachable: nodeUnreachable(err),
Missing: true}
}

var headerHex string
Expand Down Expand Up @@ -387,9 +398,11 @@ func (c *chainIdentityChecker) verifyOnce(height uint32) (chainhash.Hash,
return *nodeHash, nil
}

// waitForHeight blocks until the node's header chain reaches the activation
// waitForHeight blocks until the node's active chain reaches the activation
// height, writing the waiting status and logging while it does. It returns
// early when quit is closed.
// early when quit is closed. It waits on blocks, not headers: the check reads
// the activation block from the active chain, which a syncing node, or one
// rebuilding its chain state, has headers for long before it has the block.
func (c *chainIdentityChecker) waitForHeight(height uint32,
quit <-chan struct{}) error {

Expand All @@ -411,22 +424,23 @@ func (c *chainIdentityChecker) waitForHeight(height uint32,
"never reach block %d", info.Chain, want, height)}
}

if info.Headers >= int32(height) {
if info.Blocks >= int32(height) {
return nil
}

c.writeStatus(ChainIdentityStatus{
State: ChainIdentityWaiting,
Reason: fmt.Sprintf("waiting for the node to reach block "+
"%d (it has %d headers)", height, info.Headers),
"%d (it has %d blocks, %d headers)", height,
info.Blocks, info.Headers),
ActivationHeight: height,
NodeHeaders: info.Headers,
NodeHeaders: info.Blocks,
})
if c.now().Sub(lastLog) >= c.logInterval {
c.log.Infof("Waiting for the Bitcoin node to reach the "+
"BLAKE2b activation height %d before the chain can "+
"be identified (node has %d headers)", height,
info.Headers)
"be identified (node has %d blocks, %d headers)",
height, info.Blocks, info.Headers)
lastLog = c.now()
}

Expand Down Expand Up @@ -542,14 +556,52 @@ var errQuit = errors.New("chain identity check stopped")
// cannot answer at all (a restart, the RPC warm-up) it asks again every
// retryInterval, and only gives up after unreachableGrace. A node that
// answers with another chain is reported at once.
//
// A node that lacks the activation block while its own active chain is
// below that height, on the expected network, is waited for as long as it
// stays there: a reindex rebuilds the chain from genesis and can take hours.
// Such a node serves only blocks from before the activation, which both
// chains share, and is checked again once it has the block. A node on
// another chain with the same network name is far past that height and is
// still reported at once.
func (c *chainIdentityChecker) verifyWaiting(height uint32,
quit <-chan struct{}) (chainhash.Hash, error) {

deadline := c.now().Add(c.unreachableGrace)
logged := false
logged, loggedBehind := false, false
for {
hash, err := c.verifyOnce(height)
var wrong *ErrWrongChain
if err != nil && errors.As(err, &wrong) && wrong.Missing &&
!wrong.Unreachable {

if blocks, behind := c.nodeBehind(height); behind {
if !loggedBehind {
c.log.Warnf("The Bitcoin node's chain is at "+
"block %d, below the BLAKE2b activation "+
"block %d, as during a reindex; waiting "+
"for it to pass that block", blocks,
height)
loggedBehind = true
}
c.writeStatus(ChainIdentityStatus{
State: ChainIdentityWaiting,
Reason: fmt.Sprintf("the node's chain is at "+
"block %d, below block %d", blocks,
height),
ActivationHeight: height,
NodeHeaders: blocks,
})
deadline = c.now().Add(c.unreachableGrace)

select {
case <-time.After(c.retryInterval):
case <-quit:
return chainhash.Hash{}, errQuit
}
continue
}
}
if err == nil || !errors.As(err, &wrong) ||
!wrong.Unreachable || !c.now().Before(deadline) {

Expand All @@ -570,6 +622,22 @@ func (c *chainIdentityChecker) verifyWaiting(height uint32,
}
}

// nodeBehind reports whether the node, on the expected network, says its
// active chain has not reached height, and how far it does reach.
func (c *chainIdentityChecker) nodeBehind(height uint32) (int32, bool) {
info, err := c.rpc.GetBlockChainInfo()
if err != nil {
return 0, false
}
if want := bitcoindChainName(c.params.Params); want != "" &&
info.Chain != want {

return 0, false
}

return info.Blocks, info.Blocks < int32(height)
}

// nodeUnreachable tells a node that could not answer (connection refused or
// dropped, RPC warm-up, shutting down, overloaded) from one that answered
// something wrong.
Expand Down
128 changes: 127 additions & 1 deletion chainreg/blake2b_check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type scriptedRPC struct {
mu sync.Mutex
chain string
headers int32
blocks int32 // the active chain's height; headers when zero
infoErr error
blockHash map[int64]*chainhash.Hash
hashErr error
Expand All @@ -56,11 +57,30 @@ func (s *scriptedRPC) GetBlockChainInfo() (*btcjson.GetBlockChainInfoResult, err
if chain == "" {
chain = "main"
}
blocks := s.blocks
if blocks == 0 {
blocks = s.headers
}
return &btcjson.GetBlockChainInfoResult{
Chain: chain, Headers: s.headers, Blocks: s.headers,
Chain: chain, Headers: s.headers, Blocks: blocks,
}, nil
}

// setBlocks moves the node's active chain height while a check may be
// querying it, and serves the activation block only once the chain reaches
// it, as a node rebuilding its chain does.
func (s *scriptedRPC) setBlocks(blocks int32, activation *chainhash.Hash) {
s.mu.Lock()
defer s.mu.Unlock()

s.blocks = blocks
if blocks >= int32(Blake2bMainnetActivationHeight) {
s.blockHash[int64(Blake2bMainnetActivationHeight)] = activation
} else {
delete(s.blockHash, int64(Blake2bMainnetActivationHeight))
}
}

// setHeaders moves the node's header height while a check may be querying it.
func (s *scriptedRPC) setHeaders(headers int32) {
s.mu.Lock()
Expand Down Expand Up @@ -254,6 +274,112 @@ func TestChainIdentityWaitsForHeight(t *testing.T) {
require.Greater(t, rpc.infoCalls, 1)
}

// TestChainIdentityWaitsForBlocks: a node with every header but an active
// chain below the activation height (syncing blocks, or rebuilding its chain
// state) is waited for at startup, not refused.
func TestChainIdentityWaitsForBlocks(t *testing.T) {
dir := t.TempDir()
path := ChainIdentityStatusPath(dir, "mainnet")
rpc := mainnetRPC(t)
act := rpc.blockHash[int64(Blake2bMainnetActivationHeight)]
rpc.setBlocks(900000, act)
c := newTestChecker(t, rpc, BitcoinMainNetParams, path)

done := make(chan error, 1)
go func() {
_, err := c.run(make(chan struct{}))
done <- err
}()

require.Eventually(t, func() bool {
st, err := ReadChainIdentityStatus(path)
return err == nil && st.State == ChainIdentityWaiting &&
st.NodeHeaders == 900000
}, time.Second, time.Millisecond)
rpc.setBlocks(971774, act)

require.NoError(t, <-done)
require.Equal(t, ChainIdentityConfirmed, readStatus(t, path).State)
}

// TestChainIdentityWatchWaitsForReindex: a node that rebuilds its chain
// under a running daemon (a reindex) is waited for past the unreachable
// grace while its chain is below the activation height, and confirmed once
// it passes it. A node on another network, or one past the height that
// still lacks the block, is reported at once.
func TestChainIdentityWatchWaitsForReindex(t *testing.T) {
dir := t.TempDir()
path := ChainIdentityStatusPath(dir, "mainnet")
rpc := mainnetRPC(t)
act := rpc.blockHash[int64(Blake2bMainnetActivationHeight)]
c := newTestChecker(t, rpc, BitcoinMainNetParams, path)
_, err := c.run(make(chan struct{}))
require.NoError(t, err)
c.retryInterval = time.Millisecond
c.unreachableGrace = 5 * time.Millisecond

rpc.setBlocks(1000, act)
done := make(chan error, 1)
go func() {
_, err := c.verifyWaiting(Blake2bMainnetActivationHeight,
make(chan struct{}))
done <- err
}()

// Well past the grace, it is still waiting, and says so.
time.Sleep(100 * time.Millisecond)
select {
case err := <-done:
t.Fatalf("a reindexing node was reported: %v", err)
default:
}
st := readStatus(t, path)
require.Equal(t, ChainIdentityWaiting, st.State)
require.EqualValues(t, 1000, st.NodeHeaders)

rpc.setBlocks(971774, act)
select {
case err := <-done:
require.NoError(t, err)
case <-time.After(5 * time.Second):
t.Fatal("the check did not resume once the node had the block")
}

// The same answer from a node on another network is not waited for.
rpc.setBlocks(1000, act)
rpc.mu.Lock()
rpc.chain = "test"
rpc.mu.Unlock()
_, err = c.verifyWaiting(Blake2bMainnetActivationHeight,
make(chan struct{}))
require.ErrorContains(t, err, "out of range")

// Nor is a node whose chain is past the height but lacks the block.
rpc.mu.Lock()
rpc.chain = ""
rpc.blocks = 971774
rpc.mu.Unlock()
_, err = c.verifyWaiting(Blake2bMainnetActivationHeight,
make(chan struct{}))
require.ErrorContains(t, err, "out of range")

// Shutting down while waiting returns promptly.
rpc.setBlocks(1000, act)
quit := make(chan struct{})
go func() {
_, err := c.verifyWaiting(Blake2bMainnetActivationHeight, quit)
done <- err
}()
time.Sleep(20 * time.Millisecond)
close(quit)
select {
case err := <-done:
require.ErrorIs(t, err, errQuit)
case <-time.After(5 * time.Second):
t.Fatal("waiting on a reindexing node ignored quit")
}
}

// TestChainIdentityWaitQuits: shutting down while waiting returns promptly.
func TestChainIdentityWaitQuits(t *testing.T) {
rpc := mainnetRPC(t)
Expand Down
Loading