Skip to content

Commit 9e073fb

Browse files
committed
fix: only include the hashes for the txid we're interested in
Previously this function returned a BUMP of the whole tree which quickly exhausts ARC resources when there are thousands in memory. It should be one txid per BUMP, which is significantly less data. Signed-off-by: Darren Kellenschwiler <[email protected]>
1 parent 8859782 commit 9e073fb

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

bump.go

+11
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ func NewBUMPFromMerkleTreeAndIndex(blockHeight uint64, merkleTree []*chainhash.H
233233
return nil, errors.New("merkle tree is empty")
234234
}
235235

236+
// these are the offsets for the txid we're interested in.
236237
offsets := make([]uint64, treeHeight)
237238
for i := 0; i < treeHeight; i++ {
238239
if txIndex>>uint64(i)&1 == 0 {
@@ -251,6 +252,16 @@ func NewBUMPFromMerkleTreeAndIndex(blockHeight uint64, merkleTree []*chainhash.H
251252
bump.Path = append(bump.Path, leaves)
252253
for offset := 0; offset < numOfHashes; offset++ {
253254
o := uint64(offset)
255+
// only include the hashes for the txid we're interested in.
256+
if height == 0 {
257+
if o != txIndex && o != offsets[height] {
258+
continue
259+
}
260+
} else {
261+
if o != offsets[height] {
262+
continue
263+
}
264+
}
254265
thisLeaf := leaf{Offset: &o}
255266
hash := merkleTree[levelOffset+offset]
256267
if hash.IsEqual(nil) {

bump_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package bc
22

33
import (
4+
"math"
45
"testing"
56

67
"github.com/libsv/go-p2p/chaincfg/chainhash"
@@ -168,3 +169,27 @@ func TestTxids(t *testing.T) {
168169
txids := bump.Txids()
169170
require.Equal(t, []string{testnetBlockExample[0]}, txids)
170171
}
172+
173+
func TestOnlySpecifiedPathsStored(t *testing.T) {
174+
chainHashBlock := make([]*chainhash.Hash, 0)
175+
for _, txid := range blockTxExample {
176+
hash, err := chainhash.NewHashFromStr(txid)
177+
require.NoError(t, err)
178+
chainHashBlock = append(chainHashBlock, hash)
179+
}
180+
merkles, err := BuildMerkleTreeStoreChainHash(chainHashBlock)
181+
require.NoError(t, err)
182+
183+
for idx := range blockTxExample {
184+
bump, err := NewBUMPFromMerkleTreeAndIndex(1575794, merkles, uint64(idx))
185+
require.NoError(t, err)
186+
totalHashes := 0
187+
for _, level := range bump.Path {
188+
totalHashes += len(level)
189+
}
190+
// number of levels plus the txid itself.
191+
l := int(math.Log2(float64(len(blockTxExample)))) + 1
192+
require.Equal(t, l, totalHashes)
193+
}
194+
195+
}

0 commit comments

Comments
 (0)