Last active
July 3, 2018 15:55
-
-
Save daragao/85d98571fbe9faf95a955eb425035033 to your computer and use it in GitHub Desktop.
Example of how a transaction root is created using the Ethereum Golang libraries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"github.com/ethereum/go-ethereum/common" | |
"github.com/ethereum/go-ethereum/ethclient" | |
"github.com/ethereum/go-ethereum/ethdb" | |
"github.com/ethereum/go-ethereum/rlp" | |
"github.com/ethereum/go-ethereum/trie" | |
) | |
func main() { | |
client, err := ethclient.Dial("https://mainnet.infura.io") | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println("we have a connection") | |
header, err := client.HeaderByNumber(context.Background(), nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
block, err := client.BlockByNumber(context.Background(), header.Number) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// VERIFY TRANSACTION ROOT | |
trieObj, _ := trie.New(common.Hash{}, trie.NewDatabase(ethdb.NewMemDatabase())) // empty trie | |
for idx, tx := range block.Transactions() { | |
rlpIdx, _ := rlp.EncodeToBytes(uint(idx)) // rlp encode index of transaction | |
rlpTransaction, _ := rlp.EncodeToBytes(tx) // rlp encode transaction | |
trieObj.Update(rlpIdx, rlpTransaction) // update trie with the rlp encode index and the rlp encoded transaction | |
root, err := trieObj.Commit(nil) // commit to database (which in this case is stored in memory) | |
if err != nil { | |
log.Fatalf("commit error: %v", err) | |
} | |
txRlpHash := crypto.Keccak256Hash(rlpTransaction) | |
fmt.Printf("TxHash[%d]: \t% 0x\n\tHash(RLP(Tx)): \t% 0x\n\tTrieRoot: \t% 0x\n", | |
idx, tx.Hash().Bytes(), txRlpHash.Bytes(), root.Bytes()) | |
} | |
fmt.Printf("\n\nBlock number: %d \n\tBlock.TxHash:\t% 0x \n\tTrie.Root:\t% 0x\n", | |
block.Number, block.TxHash().Bytes(), trieObj.Root()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment