lbcwallet/wallet/wallet_test.go
Wilmer Paulino 2a6f24c61b
wallet: locate birthday block without scanning chain from genesis
We do this as the wallet will no longer store blocks all the way from
genesis to the tip of the chain. Instead, in order to find a reasonable
birthday block, we resort to performing a binary search for a block
timestamp that's within +/-2 hours of the birthday timestamp.
2019-06-13 18:09:01 -07:00

85 lines
2.2 KiB
Go

package wallet
import (
"testing"
"time"
)
// TestLocateBirthdayBlock ensures we can properly map a block in the chain to a
//timestamp.
func TestLocateBirthdayBlock(t *testing.T) {
t.Parallel()
// We'll use test chains of 30 blocks with a duration between two
// consecutive blocks being slightly greater than the largest margin
// allowed by locateBirthdayBlock. Doing so lets us test the method more
// effectively as there is only one block within the chain that can map
// to a timestamp (this does not apply to the first and last blocks,
// which can map to many timestamps beyond either end of chain).
const (
numBlocks = 30
blockInterval = birthdayBlockDelta + 1
)
genesisTimestamp := chainParams.GenesisBlock.Header.Timestamp
testCases := []struct {
name string
birthday time.Time
birthdayHeight int32
}{
{
name: "left-right-left-left",
birthday: genesisTimestamp.Add(8 * blockInterval),
birthdayHeight: 8,
},
{
name: "right-right-right-left",
birthday: genesisTimestamp.Add(27 * blockInterval),
birthdayHeight: 27,
},
{
name: "before start height",
birthday: genesisTimestamp.Add(-blockInterval),
birthdayHeight: 0,
},
{
name: "start height",
birthday: genesisTimestamp,
birthdayHeight: 0,
},
{
name: "end height",
birthday: genesisTimestamp.Add(numBlocks * blockInterval),
birthdayHeight: numBlocks - 1,
},
{
name: "after end height",
birthday: genesisTimestamp.Add(2 * numBlocks * blockInterval),
birthdayHeight: numBlocks - 1,
},
}
for _, testCase := range testCases {
success := t.Run(testCase.name, func(t *testing.T) {
chainConn := createMockChainConn(
chainParams.GenesisBlock, numBlocks, blockInterval,
)
birthdayBlock, err := locateBirthdayBlock(
chainConn, testCase.birthday,
)
if err != nil {
t.Fatalf("unable to locate birthday block: %v",
err)
}
if birthdayBlock.Height != testCase.birthdayHeight {
t.Fatalf("expected birthday block with height "+
"%d, got %d", testCase.birthdayHeight,
birthdayBlock.Height)
}
})
if !success {
break
}
}
}