Skip to content

Commit

Permalink
fix: only include the hashes for the txid we're interested in
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
sirdeggen committed Dec 1, 2023
1 parent 8859782 commit 9e073fb
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
11 changes: 11 additions & 0 deletions bump.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ func NewBUMPFromMerkleTreeAndIndex(blockHeight uint64, merkleTree []*chainhash.H
return nil, errors.New("merkle tree is empty")
}

// these are the offsets for the txid we're interested in.
offsets := make([]uint64, treeHeight)
for i := 0; i < treeHeight; i++ {
if txIndex>>uint64(i)&1 == 0 {
Expand All @@ -251,6 +252,16 @@ func NewBUMPFromMerkleTreeAndIndex(blockHeight uint64, merkleTree []*chainhash.H
bump.Path = append(bump.Path, leaves)
for offset := 0; offset < numOfHashes; offset++ {
o := uint64(offset)
// only include the hashes for the txid we're interested in.
if height == 0 {
if o != txIndex && o != offsets[height] {
continue
}
} else {
if o != offsets[height] {
continue
}
}
thisLeaf := leaf{Offset: &o}
hash := merkleTree[levelOffset+offset]
if hash.IsEqual(nil) {
Expand Down
25 changes: 25 additions & 0 deletions bump_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package bc

import (
"math"
"testing"

"github.com/libsv/go-p2p/chaincfg/chainhash"
Expand Down Expand Up @@ -168,3 +169,27 @@ func TestTxids(t *testing.T) {
txids := bump.Txids()
require.Equal(t, []string{testnetBlockExample[0]}, txids)
}

func TestOnlySpecifiedPathsStored(t *testing.T) {
chainHashBlock := make([]*chainhash.Hash, 0)
for _, txid := range blockTxExample {
hash, err := chainhash.NewHashFromStr(txid)
require.NoError(t, err)
chainHashBlock = append(chainHashBlock, hash)
}
merkles, err := BuildMerkleTreeStoreChainHash(chainHashBlock)
require.NoError(t, err)

for idx := range blockTxExample {
bump, err := NewBUMPFromMerkleTreeAndIndex(1575794, merkles, uint64(idx))
require.NoError(t, err)
totalHashes := 0
for _, level := range bump.Path {
totalHashes += len(level)
}
// number of levels plus the txid itself.
l := int(math.Log2(float64(len(blockTxExample)))) + 1
require.Equal(t, l, totalHashes)
}

}

0 comments on commit 9e073fb

Please sign in to comment.