Beispiel #1
0
        private void CreateBranchNodes()
        {
            if (m_LeafNodes.Count == 0)
            {
                Console.WriteLine("Error: no leaves were found!");
                return;
            }

            if (m_IsPerfCounterOn)
            {
                m_StopWatch.Start();
            }

            var childNodes = m_LeafNodes.Values.ToList();

            // Recurse the nodes
            while (true)
            {
                if (childNodes.Count == 1)
                {
                    m_MerkleRoot = m_LeafNodes[0];
                }
                else
                {
                    // Holds a list of all the nodes above the child nodes
                    var parentNodes = new List <MerkleNode>();

                    for (var i = 0; i < childNodes.Count; i += 2)
                    {
                        // Get two current nodes
                        var leftNode  = childNodes[i];
                        var rightNode = i + 1 < childNodes.Count ? childNodes[i + 1] : null;

                        // Create the parent of these two children
                        var parent = CreateBranchNode(leftNode, rightNode);

                        // Set the new parent node on the children
                        leftNode.SetParent(parent);
                        rightNode?.SetParent(parent);

                        // Add the two child nodes to the Merkle Tree only if they are not leaves
                        if (!leftNode.IsLeafNode)
                        {
                            m_BranchNodes.Add(leftNode);
                        }

                        if (rightNode != null && !rightNode.IsLeafNode)
                        {
                            m_BranchNodes.Add(rightNode);
                        }

                        parentNodes.Add(parent);

                        if (m_IsVerboseMode)
                        {
                            Console.WriteLine($"Level:{Levels}, Node:{parent.Hash.ToHexString()}");
                        }
                    }

                    Levels++;

                    // Parent nodes become the children, and reiterate
                    childNodes = parentNodes;

                    continue;
                }

                break;
            }

            if (m_IsPerfCounterOn)
            {
                m_StopWatch.Stop();
                Console.WriteLine($"Generated {m_BranchNodes.Count} Merkle Nodes in {m_StopWatch.ElapsedMilliseconds}ms.\n");
                m_StopWatch.Reset();
            }
        }