Skip to content

Instantly share code, notes, and snippets.

@theStack
Created April 14, 2023 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theStack/53e5a5c8b31d78d54b5cf427868e6bf3 to your computer and use it in GitHub Desktop.
Save theStack/53e5a5c8b31d78d54b5cf427868e6bf3 to your computer and use it in GitHub Desktop.
utreexo README.md example, corrected
package main
import (
"crypto/sha256"
"fmt"
"github.com/utreexo/utreexo"
"os"
)
func main() {
fmt.Println("===== utreexo README.md example =====")
fmt.Println("-> Initialize Prover and Verifier")
// Prover supports all 4 operations.
prover := utreexo.NewAccumulator(true)
// Verifer does not support proving elements.
verifier := utreexo.Stump{}
// A verifier may keep the below to cache the leaves and the merkle branches
// for some of the elements.
cachedHashes := []utreexo.Hash{}
cachedProof := utreexo.Proof{}
fmt.Println("-> Add elements")
data := []string{"utxo1", "utxo2", "utxo3", "utxo4"}
// Hash the data as the accumulator expects []utreexo.Hash (utreexo.Hash is just [32]byte).
// These hashes are commitments to the elements we're adding.
hashes := make([]utreexo.Hash, len(data))
leaves := make([]utreexo.Leaf, len(data))
for i, d := range data {
hash := sha256.Sum256([]byte(d))
hashes[i] = hash
leaves[i] = utreexo.Leaf{Hash: hash}
}
// Add the elements to the prover and the verifier.
prover.Modify(leaves, nil, nil)
updateData, _ := verifier.Update(nil, hashes, utreexo.Proof{})
// If we want to cache the proof for "utxo4", we give the index of the element to cache.
rememberIndexes := []uint32{3}
cachedHashes, _ = cachedProof.Update(cachedHashes, hashes, nil, rememberIndexes, updateData)
fmt.Println("-> Delete elements")
// Now let's delete the element "utxo1" from the accumulator.
//
// For deletion, we first need to first prove the hashes of the elements being deleted.
proof, _ := prover.Prove(hashes[:1])
// Delete "utxo1" from the accumulator.
prover.Modify(nil, hashes[:1], proof.Targets)
// For the verifier, we need to first verify the proof before updating the state as
// the prover may give out false proofs.
_, err := utreexo.Verify(verifier, hashes[:1], proof)
if err != nil {
fmt.Printf("Verify fail for proof %s. Error: %v\n", proof.String(), err)
os.Exit(1)
}
// If the proof is correct, we can now modify the state of the verifier and delete "utxo1".
updateData, _ = verifier.Update(hashes[:1], nil, proof)
// Update the proof cache.
cachedHashes, _ = cachedProof.Update(cachedHashes, hashes[:1], proof.Targets, nil, updateData)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment