Skip to content

Commit

Permalink
adding the merkle tree logic
Browse files Browse the repository at this point in the history
  • Loading branch information
OsauravO committed Apr 25, 2024
1 parent 6325760 commit f4bf6e6
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,56 @@ func CreateCoinbase(netReward uint64) *Transaction {
}
return &coinbaseTx
}
func NewMerkleNode(lnode *MerkleNode, rnode *MerkleNode, data []byte) *MerkleNode {
var mNode MerkleNode = MerkleNode{}
if lnode == nil && rnode == nil {
//hash256 of the data
mNode.Data = ReverseBytes(data)
} else {
var prevHash []byte = append(lnode.Data, rnode.Data...)
mNode.Data = To_sha(To_sha(prevHash))
}
mNode.Left = lnode
mNode.Right = rnode
return &mNode
}

func NewMerkleTree(leaves []string) *MerkleNode {
var nodes []MerkleNode

for _, leaf := range leaves {
data, _ := hex.DecodeString(leaf)
var node MerkleNode = *NewMerkleNode(nil, nil, data)
nodes = append(nodes, node)
}

for len(nodes) > 1 {
var newLevel []MerkleNode
for i := 0; i < len(nodes); i += 2 {
// Handle case where the total number of nodes is odd.
if len(nodes)%2 != 0 {
nodes = append(nodes, nodes[len(nodes)-1])
}
node := *NewMerkleNode(&nodes[i], &nodes[i+1], nil)
newLevel = append(newLevel, node)
}
nodes = newLevel
}
return &nodes[0]

}

func CreateWitnessMerkle() string {
_, _, wTxIDs := Prioritize()
wTxIDs = append([]string{"0000000000000000000000000000000000000000000000000000000000000000"}, wTxIDs...)
merkleRoot := NewMerkleTree(wTxIDs)
fmt.Println("WMKR: ", hex.EncodeToString(merkleRoot.Data))
commitment_string := hex.EncodeToString(merkleRoot.Data) + "0000000000000000000000000000000000000000000000000000000000000000"
WitnessCommitment, _ := hex.DecodeString(commitment_string)
WitnessCommitment = To_sha(To_sha(WitnessCommitment))
fmt.Println("Witness Commitment: ", hex.EncodeToString(WitnessCommitment))
return hex.EncodeToString(WitnessCommitment)
}

func main() {
networkReward, transactionIDs, _ := Prioritize()
Expand Down

0 comments on commit f4bf6e6

Please sign in to comment.