From 19b0a6836b180f136bf03425e463efbe475e11e3 Mon Sep 17 00:00:00 2001 From: Nithish Karthik Date: Thu, 11 Apr 2024 23:43:15 +0530 Subject: [PATCH] use simple merkle tree calculator --- src/mining/merkle_tree.go | 33 +++++++++++++++++++++++++++++++++ src/mining/mining.go | 6 +++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/mining/merkle_tree.go b/src/mining/merkle_tree.go index da1eb4e..b17e174 100644 --- a/src/mining/merkle_tree.go +++ b/src/mining/merkle_tree.go @@ -68,6 +68,39 @@ func (s *rollingMerkleTreeStore) add(add [32]byte) { s.numLeaves++ } +func GenerateMerkleTreeRoot(txids [][32]byte) [32]byte{ + // reverse the txids + level := make([][32]byte, 0) + for _, t := range txids { + level = append(level, [32]byte(utils.ReverseBytes(t[:]))) + } + + for len(level) > 1 { + nextLevel := make([][32]byte, 0) + + for i := 0; i < len(level); i += 2 { + var pairHash [32]byte + if (i + 1 == len(level)) { + // In case of an odd number of elements, duplicate the last one + var x [64]byte + copy(x[:32], level[i][:]) + copy(x[32:], level[i][:]) + pairHash = utils.DoubleHashRaw(x[:]) + } else { + var x [64]byte + copy(x[:32], level[i][:]) + copy(x[32:], level[i+1][:]) + pairHash = utils.DoubleHashRaw(x[:]) + } + nextLevel = append(nextLevel, pairHash) + } + + level = nextLevel + } + + return level[0] +} + func CalcMerkleRoot(transactions []*transaction.Transaction, witness bool) [32]byte { s := newRollingMerkleTreeStore(uint64(len(transactions))) diff --git a/src/mining/mining.go b/src/mining/mining.go index c73b606..6f135b5 100644 --- a/src/mining/mining.go +++ b/src/mining/mining.go @@ -49,7 +49,11 @@ func GetCandidateBlock(txns []*txn.Transaction, hasWitness bool) Block { // header nBits := TargetToNbits(tarDif) prevBH,_ := hex.DecodeString(prevBlockHash) - header := NewBlockHeader(BlockVersion, *utils.NewHash(prevBH), CalcMerkleRoot(blockTxns, false), time.Now().Unix(),nBits, 0) + txids := make([][32]byte, 0) + for _, t := range blockTxns { + txids = append(txids, [32]byte(utils.ReverseBytes(t.TxHash()))) + } + header := NewBlockHeader(BlockVersion, *utils.NewHash(prevBH), GenerateMerkleTreeRoot(txids), time.Now().Unix(),nBits, 0) candidateBlock.BlockHeader = header // transactions