github.com/MetalBlockchain/metalgo@v1.11.9/x/merkledb/node_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  	"io"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/require"
    11  
    12  	"github.com/MetalBlockchain/metalgo/utils/maybe"
    13  )
    14  
    15  func Test_Node_Marshal(t *testing.T) {
    16  	root := newNode(Key{})
    17  	require.NotNil(t, root)
    18  
    19  	fullKey := ToKey([]byte("key"))
    20  	childNode := newNode(fullKey)
    21  	root.addChild(childNode, 4)
    22  	childNode.setValue(DefaultHasher, maybe.Some([]byte("value")))
    23  	require.NotNil(t, childNode)
    24  
    25  	root.addChild(childNode, 4)
    26  
    27  	data := root.bytes()
    28  	rootParsed, err := parseNode(DefaultHasher, ToKey([]byte("")), data)
    29  	require.NoError(t, err)
    30  	require.Len(t, rootParsed.children, 1)
    31  
    32  	rootIndex := getSingleChildKey(root, 4).Token(0, 4)
    33  	parsedIndex := getSingleChildKey(rootParsed, 4).Token(0, 4)
    34  	rootChildEntry := root.children[rootIndex]
    35  	parseChildEntry := rootParsed.children[parsedIndex]
    36  	require.Equal(t, rootChildEntry.id, parseChildEntry.id)
    37  }
    38  
    39  func Test_Node_Marshal_Errors(t *testing.T) {
    40  	root := newNode(Key{})
    41  	require.NotNil(t, root)
    42  
    43  	fullKey := ToKey([]byte{255})
    44  	childNode1 := newNode(fullKey)
    45  	root.addChild(childNode1, 4)
    46  	childNode1.setValue(DefaultHasher, maybe.Some([]byte("value1")))
    47  	require.NotNil(t, childNode1)
    48  
    49  	root.addChild(childNode1, 4)
    50  
    51  	fullKey = ToKey([]byte{237})
    52  	childNode2 := newNode(fullKey)
    53  	root.addChild(childNode2, 4)
    54  	childNode2.setValue(DefaultHasher, maybe.Some([]byte("value2")))
    55  	require.NotNil(t, childNode2)
    56  
    57  	root.addChild(childNode2, 4)
    58  
    59  	data := root.bytes()
    60  
    61  	for i := 1; i < len(data); i++ {
    62  		broken := data[:i]
    63  		_, err := parseNode(DefaultHasher, ToKey([]byte("")), broken)
    64  		require.ErrorIs(t, err, io.ErrUnexpectedEOF)
    65  	}
    66  }