lbcd/database2/internal/treap/common_test.go

122 lines
3 KiB
Go
Raw Normal View History

database: Major redesign of database package. This commit contains a complete redesign and rewrite of the database package that approaches things in a vastly different manner than the previous version. This is the first part of several stages that will be needed to ultimately make use of this new package. Some of the reason for this were discussed in #255, however a quick summary is as follows: - The previous database could only contain blocks on the main chain and reorgs required deleting the blocks from the database. This made it impossible to store orphans and could make external RPC calls for information about blocks during the middle of a reorg fail. - The previous database interface forced a high level of bitcoin-specific intelligence such as spend tracking into each backend driver. - The aforementioned point led to making it difficult to implement new backend drivers due to the need to repeat a lot of non-trivial logic which is better handled at a higher layer, such as the blockchain package. - The old database stored all blocks in leveldb. This made it extremely inefficient to do things such as lookup headers and individual transactions since the entire block had to be loaded from leveldb (which entails it doing data copies) to get access. In order to address all of these concerns, and others not mentioned, the database interface has been redesigned as follows: - Two main categories of functionality are provided: block storage and metadata storage - All block storage and metadata storage are done via read-only and read-write MVCC transactions with both manual and managed modes - Support for multiple concurrent readers and a single writer - Readers use a snapshot and therefore are not blocked by the writer - Some key properties of the block storage and retrieval API: - It is generic and does NOT contain additional bitcoin logic such spend tracking and block linking - Provides access to the raw serialized bytes so deserialization is not forced for callers that don't need it - Support for fetching headers via independent functions which allows implementations to provide significant optimizations - Ability to efficiently retrieve arbitrary regions of blocks (transactions, scripts, etc) - A rich metadata storage API is provided: - Key/value with arbitrary data - Support for buckets and nested buckets - Bucket iteration through a couple of different mechanisms - Cursors for efficient and direct key seeking - Supports registration of backend database implementations - Comprehensive test coverage - Provides strong documentation with example usage This commit also contains an implementation of the previously discussed interface named ffldb (flat file plus leveldb metadata backend). Here is a quick overview: - Highly optimized for read performance with consistent write performance regardless of database size - All blocks are stored in flat files on the file system - Bulk block region fetching is optimized to perform linear reads which improves performance on spindle disks - Anti-corruption mechanisms: - Flat files contain full block checksums to quickly an easily detect database corruption without needing to do expensive merkle root calculations - Metadata checksums - Open reconciliation - Extensive test coverage: - Comprehensive blackbox interface testing - Whitebox testing which uses intimate knowledge to exercise uncommon failure paths such as deleting files out from under the database - Corruption tests (replacing random data in the files) In addition, this commit also contains a new tool under the new database directory named dbtool which provides a few basic commands for testing the database. It is designed around commands, so it could be useful to expand on in the future. Finally, this commit addresses the following issues: - Adds support for and therefore closes #255 - Fixes #199 - Fixes #201 - Implements and closes #256 - Obsoletes and closes #257 - Closes #247 once the required chain and btcd modifications are in place to make use of this new code
2016-02-03 18:42:04 +01:00
// Copyright (c) 2015-2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package treap
import (
"encoding/binary"
"encoding/hex"
"math/rand"
"reflect"
"testing"
)
// fromHex converts the passed hex string into a byte slice and will panic if
// there is an error. This is only provided for the hard-coded constants so
// errors in the source code can be detected. It will only (and must only) be
// called for initialization purposes.
func fromHex(s string) []byte {
r, err := hex.DecodeString(s)
if err != nil {
panic("invalid hex in source file: " + s)
}
return r
}
// serializeUint32 returns the big-endian encoding of the passed uint32.
func serializeUint32(ui uint32) []byte {
var ret [4]byte
binary.BigEndian.PutUint32(ret[:], ui)
return ret[:]
}
// TestParentStack ensures the treapParentStack functionality works as intended.
func TestParentStack(t *testing.T) {
t.Parallel()
tests := []struct {
numNodes int
}{
{numNodes: 1},
{numNodes: staticDepth},
{numNodes: staticDepth + 1}, // Test dynamic code paths
}
testLoop:
for i, test := range tests {
nodes := make([]*treapNode, 0, test.numNodes)
for j := 0; j < test.numNodes; j++ {
var key [4]byte
binary.BigEndian.PutUint32(key[:], uint32(j))
node := newTreapNode(key[:], key[:], 0)
nodes = append(nodes, node)
}
// Push all of the nodes onto the parent stack while testing
// various stack properties.
stack := &parentStack{}
for j, node := range nodes {
stack.Push(node)
// Ensure the stack length is the expected value.
if stack.Len() != j+1 {
t.Errorf("Len #%d (%d): unexpected stack "+
"length - got %d, want %d", i, j,
stack.Len(), j+1)
continue testLoop
}
// Ensure the node at each index is the expected one.
for k := 0; k <= j; k++ {
atNode := stack.At(j - k)
if !reflect.DeepEqual(atNode, nodes[k]) {
t.Errorf("At #%d (%d): mismatched node "+
"- got %v, want %v", i, j-k,
atNode, nodes[k])
continue testLoop
}
}
}
// Ensure each popped node is the expected one.
for j := 0; j < len(nodes); j++ {
node := stack.Pop()
expected := nodes[len(nodes)-j-1]
if !reflect.DeepEqual(node, expected) {
t.Errorf("At #%d (%d): mismatched node - "+
"got %v, want %v", i, j, node, expected)
continue testLoop
}
}
// Ensure the stack is now empty.
if stack.Len() != 0 {
t.Errorf("Len #%d: stack is not empty - got %d", i,
stack.Len())
continue testLoop
}
// Ensure attempting to retrieve a node at an index beyond the
// stack's length returns nil.
if node := stack.At(2); node != nil {
t.Errorf("At #%d: did not give back nil - got %v", i,
node)
continue testLoop
}
// Ensure attempting to pop a node from an empty stack returns
// nil.
if node := stack.Pop(); node != nil {
t.Errorf("Pop #%d: did not give back nil - got %v", i,
node)
continue testLoop
}
}
}
func init() {
// Force the same pseudo random numbers for each test run.
rand.Seed(0)
}