@@ -130,10 +130,23 @@ static void MerkleComputation(const std::vector<uint256>& leaves, uint256* proot
130
130
if (proot) *proot = h;
131
131
}
132
132
133
- uint256 ComputeMerkleRoot (const std::vector<uint256>& leaves, bool * mutated) {
134
- uint256 hash;
135
- MerkleComputation (leaves, &hash, mutated, -1 , nullptr );
136
- return hash;
133
+ uint256 ComputeMerkleRoot (std::vector<uint256> hashes, bool * mutated) {
134
+ bool mutation = false ;
135
+ while (hashes.size () > 1 ) {
136
+ if (mutated) {
137
+ for (size_t pos = 0 ; pos + 1 < hashes.size (); pos += 2 ) {
138
+ if (hashes[pos] == hashes[pos + 1 ]) mutation = true ;
139
+ }
140
+ }
141
+ if (hashes.size () & 1 ) {
142
+ hashes.push_back (hashes.back ());
143
+ }
144
+ SHA256D64 (hashes[0 ].begin (), hashes[0 ].begin (), hashes.size () / 2 );
145
+ hashes.resize (hashes.size () / 2 );
146
+ }
147
+ if (mutated) *mutated = mutation;
148
+ if (hashes.size () == 0 ) return uint256 ();
149
+ return hashes[0 ];
137
150
}
138
151
139
152
std::vector<uint256> ComputeMerkleBranch (const std::vector<uint256>& leaves, uint32_t position) {
@@ -162,7 +175,7 @@ uint256 BlockMerkleRoot(const CBlock& block, bool* mutated)
162
175
for (size_t s = 0 ; s < block.vtx .size (); s++) {
163
176
leaves[s] = block.vtx [s]->GetHash ();
164
177
}
165
- return ComputeMerkleRoot (leaves, mutated);
178
+ return ComputeMerkleRoot (std::move ( leaves) , mutated);
166
179
}
167
180
168
181
uint256 BlockWitnessMerkleRoot (const CBlock& block, bool * mutated)
@@ -173,7 +186,7 @@ uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated)
173
186
for (size_t s = 1 ; s < block.vtx .size (); s++) {
174
187
leaves[s] = block.vtx [s]->GetWitnessHash ();
175
188
}
176
- return ComputeMerkleRoot (leaves, mutated);
189
+ return ComputeMerkleRoot (std::move ( leaves) , mutated);
177
190
}
178
191
179
192
std::vector<uint256> BlockMerkleBranch (const CBlock& block, uint32_t position)
0 commit comments