Skip to content

Commit

Permalink
merkle root is the txid if there is only one (#75)
Browse files Browse the repository at this point in the history
Signed-off-by: Darren Kellenschwiler <d.kellenschwiler@bsvblockchain.org>
  • Loading branch information
sirdeggen authored Nov 3, 2023
1 parent 58361c8 commit c4b255f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
5 changes: 4 additions & 1 deletion bump.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ func (bump *BUMP) String() (string, error) {

// CalculateRootGivenTxid calculates the root of the Merkle tree given a txid.
func (bump *BUMP) CalculateRootGivenTxid(txid string) (string, error) {
if len(bump.Path) < 2 {
return txid, nil
}
// Find the index of the txid at the lowest level of the Merkle tree
var index uint64
txidFound := false
Expand Down Expand Up @@ -241,7 +244,7 @@ func NewBUMPFromMerkleTreeAndIndex(blockHeight uint64, merkleTree []*chainhash.H
} else {
sh := merkleTree[0].String()
o := uint64(0)
bump.Path[0][0] = leaf{Hash: &sh, Offset: &o, Txid: &t}
bump.Path = [][]leaf{{leaf{Hash: &sh, Offset: &o, Txid: &t}}}
}

return bump, nil
Expand Down
15 changes: 15 additions & 0 deletions bump_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const (
txidExample = `3ecead27a44d013ad1aae40038acbb1883ac9242406808bb4667c15b4f164eac`
rootOfBlockTxExample = `1a1e779cd7dfc59f603b4e88842121001af822b2dc5d3b167ae66152e586a6b0`
fakeMadeUpNum = 814435
txidSmallBlock = `be7853d7685ed5b5ec61a0ca8e3f193a7b0632cb2db950528c2041ee5d7dd95d`
)

var blockTxExample = []string{
Expand All @@ -28,6 +29,20 @@ var blockTxExample = []string{
"397fe2ae4d1d24efcc868a02daae42d1b419289d9a1ded3a5fe771efcc1219d9",
}

func TestNewBUMPFromMerkleTreeWithOnlyOneTxid(t *testing.T) {
chainHashBlock := make([]*chainhash.Hash, 0)
hash, err := chainhash.NewHashFromStr(txidSmallBlock)
require.NoError(t, err)
chainHashBlock = append(chainHashBlock, hash)
merkles, err := BuildMerkleTreeStoreChainHash(chainHashBlock)
require.NoError(t, err)
bump, err := NewBUMPFromMerkleTreeAndIndex(fakeMadeUpNum, merkles, uint64(0))
require.NoError(t, err)
root, err := bump.CalculateRootGivenTxid(txidSmallBlock)
require.NoError(t, err)
require.Equal(t, txidSmallBlock, root)
}

func TestNewBUMPFromMerkleTree(t *testing.T) {
chainHashBlock := make([]*chainhash.Hash, 0)
for _, txid := range blockTxExample {
Expand Down

0 comments on commit c4b255f

Please sign in to comment.