Exemple #1
0
func TestPersistence(t *testing.T) {
	db := db.NewMemDB()

	// Create some random key value pairs
	records := make(map[string]string)
	for i := 0; i < 10000; i++ {
		records[randstr(20)] = randstr(20)
	}

	// Construct some tree and save it
	t1 := NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 0, db)
	for key, value := range records {
		t1.Set(key, value)
	}
	t1.Save()

	hash, _ := t1.HashWithCount()

	// Load a tree
	t2 := NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 0, db)
	t2.Load(hash)
	for key, value := range records {
		_, t2value := t2.Get(key)
		if t2value != value {
			t.Fatalf("Invalid value. Expected %v, got %v", value, t2value)
		}
	}
}
Exemple #2
0
func TestIAVLProof(t *testing.T) {

	// Convenient wrapper around wire.BasicCodec.
	toBytes := func(o interface{}) []byte {
		buf, n, err := new(bytes.Buffer), int64(0), error(nil)
		wire.BasicCodec.Encode(o, buf, &n, &err)
		if err != nil {
			panic(Fmt("Failed to encode thing: %v", err))
		}
		return buf.Bytes()
	}

	// Construct some random tree
	db := db.NewMemDB()
	var tree *IAVLTree = NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 100, db)
	for i := 0; i < 1000; i++ {
		key, value := randstr(20), randstr(20)
		tree.Set(key, value)
	}

	// Persist the items so far
	tree.Save()

	// Add more items so it's not all persisted
	for i := 0; i < 100; i++ {
		key, value := randstr(20), randstr(20)
		tree.Set(key, value)
	}

	// Now for each item, construct a proof and verify
	tree.Iterate(func(key interface{}, value interface{}) bool {
		proof := tree.ConstructProof(key)
		if !bytes.Equal(proof.RootHash, tree.Hash()) {
			t.Errorf("Invalid proof. Expected root %X, got %X", tree.Hash(), proof.RootHash)
		}
		testProof(t, proof, toBytes(key), toBytes(value), tree.Hash())
		return false
	})

}