-
Notifications
You must be signed in to change notification settings - Fork 70
/
branch.go
68 lines (56 loc) · 1.26 KB
/
branch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"github.com/ethereum/go-ethereum/crypto"
)
type BranchNode struct {
Branches [16]Node
Value []byte
}
func NewBranchNode() *BranchNode {
return &BranchNode{
Branches: [16]Node{},
}
}
func (b BranchNode) Hash() []byte {
return crypto.Keccak256(b.Serialize())
}
func (b *BranchNode) SetBranch(nibble Nibble, node Node) {
b.Branches[int(nibble)] = node
}
func (b *BranchNode) RemoveBranch(nibble Nibble) {
b.Branches[int(nibble)] = nil
}
func (b *BranchNode) SetValue(value []byte) {
b.Value = value
}
func (b *BranchNode) RemoveValue() {
b.Value = nil
}
func (b BranchNode) Raw() []interface{} {
hashes := make([]interface{}, 17)
for i := 0; i < 16; i++ {
if b.Branches[i] == nil {
hashes[i] = EmptyNodeRaw
} else {
node := b.Branches[i]
if len(Serialize(node)) >= 32 {
hashes[i] = node.Hash()
} else {
// if node can be serialized to less than 32 bits, then
// use Serialized directly.
// it has to be ">=", rather than ">",
// so that when deserialized, the content can be distinguished
// by length
hashes[i] = node.Raw()
}
}
}
hashes[16] = b.Value
return hashes
}
func (b BranchNode) Serialize() []byte {
return Serialize(b)
}
func (b BranchNode) HasValue() bool {
return b.Value != nil
}