github.com/MetalBlockchain/metalgo@v1.11.9/x/merkledb/helpers_test.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package merkledb 5 6 import ( 7 "context" 8 "math/rand" 9 "testing" 10 11 "github.com/stretchr/testify/require" 12 13 "github.com/MetalBlockchain/metalgo/database/memdb" 14 "github.com/MetalBlockchain/metalgo/ids" 15 "github.com/MetalBlockchain/metalgo/utils/hashing" 16 "github.com/MetalBlockchain/metalgo/utils/maybe" 17 ) 18 19 func getBasicDB() (*merkleDB, error) { 20 return newDatabase( 21 context.Background(), 22 memdb.New(), 23 newDefaultConfig(), 24 &mockMetrics{}, 25 ) 26 } 27 28 func getBasicDBWithBranchFactor(bf BranchFactor) (*merkleDB, error) { 29 config := newDefaultConfig() 30 config.BranchFactor = bf 31 return newDatabase( 32 context.Background(), 33 memdb.New(), 34 config, 35 &mockMetrics{}, 36 ) 37 } 38 39 // Writes []byte{i} -> []byte{i} for i in [0, 4] 40 func writeBasicBatch(t *testing.T, db *merkleDB) { 41 require := require.New(t) 42 43 batch := db.NewBatch() 44 require.NoError(batch.Put([]byte{0}, []byte{0})) 45 require.NoError(batch.Put([]byte{1}, []byte{1})) 46 require.NoError(batch.Put([]byte{2}, []byte{2})) 47 require.NoError(batch.Put([]byte{3}, []byte{3})) 48 require.NoError(batch.Put([]byte{4}, []byte{4})) 49 require.NoError(batch.Write()) 50 } 51 52 func newRandomProofNode(r *rand.Rand) ProofNode { 53 key := make([]byte, r.Intn(32)) // #nosec G404 54 _, _ = r.Read(key) // #nosec G404 55 serializedKey := ToKey(key) 56 57 val := make([]byte, r.Intn(64)) // #nosec G404 58 _, _ = r.Read(val) // #nosec G404 59 60 children := map[byte]ids.ID{} 61 for j := 0; j < 16; j++ { 62 if r.Float64() < 0.5 { 63 var childID ids.ID 64 _, _ = r.Read(childID[:]) // #nosec G404 65 children[byte(j)] = childID 66 } 67 } 68 69 hasValue := rand.Intn(2) == 1 // #nosec G404 70 var valueOrHash maybe.Maybe[[]byte] 71 if hasValue { 72 // use the hash instead when length is greater than the hash length 73 if len(val) >= HashLength { 74 val = hashing.ComputeHash256(val) 75 } else if len(val) == 0 { 76 // We do this because when we encode a value of []byte{} we will later 77 // decode it as nil. 78 // Doing this prevents inconsistency when comparing the encoded and 79 // decoded values. 80 val = nil 81 } 82 valueOrHash = maybe.Some(val) 83 } 84 85 return ProofNode{ 86 Key: serializedKey, 87 ValueOrHash: valueOrHash, 88 Children: children, 89 } 90 }