ethtrie.NewTrie => ethtrie.New

This commit is contained in:
obscuren 2014-08-04 10:38:18 +02:00
parent 2e7cf83522
commit 3debeb7236
8 changed files with 52 additions and 82 deletions

View File

@ -100,7 +100,7 @@ func CreateBlock(root interface{},
} }
block.SetUncles([]*Block{}) block.SetUncles([]*Block{})
block.state = ethstate.NewState(ethtrie.NewTrie(ethutil.Config.Db, root)) block.state = ethstate.NewState(ethtrie.New(ethutil.Config.Db, root))
return block return block
} }
@ -220,26 +220,10 @@ func (self *Block) SetReceipts(receipts []*Receipt, txs []*Transaction) {
func (block *Block) setTransactions(txs []*Transaction) { func (block *Block) setTransactions(txs []*Transaction) {
block.transactions = txs block.transactions = txs
/*
trie := ethtrie.NewTrie(ethutil.Config.Db, "")
for i, tx := range txs {
trie.Update(strconv.Itoa(i), string(tx.RlpEncode()))
}
switch trie.Root.(type) {
case string:
block.TxSha = []byte(trie.Root.(string))
case []byte:
block.TxSha = trie.Root.([]byte)
default:
panic(fmt.Sprintf("invalid root type %T", trie.Root))
}
*/
} }
func CreateTxSha(receipts Receipts) (sha []byte) { func CreateTxSha(receipts Receipts) (sha []byte) {
trie := ethtrie.NewTrie(ethutil.Config.Db, "") trie := ethtrie.New(ethutil.Config.Db, "")
for i, receipt := range receipts { for i, receipt := range receipts {
trie.Update(string(ethutil.NewValue(i).Encode()), string(ethutil.NewValue(receipt.RlpData()).Encode())) trie.Update(string(ethutil.NewValue(i).Encode()), string(ethutil.NewValue(receipt.RlpData()).Encode()))
} }
@ -281,7 +265,7 @@ func (block *Block) RlpValueDecode(decoder *ethutil.Value) {
block.PrevHash = header.Get(0).Bytes() block.PrevHash = header.Get(0).Bytes()
block.UncleSha = header.Get(1).Bytes() block.UncleSha = header.Get(1).Bytes()
block.Coinbase = header.Get(2).Bytes() block.Coinbase = header.Get(2).Bytes()
block.state = ethstate.NewState(ethtrie.NewTrie(ethutil.Config.Db, header.Get(3).Val)) block.state = ethstate.NewState(ethtrie.New(ethutil.Config.Db, header.Get(3).Val))
block.TxSha = header.Get(4).Bytes() block.TxSha = header.Get(4).Bytes()
block.Difficulty = header.Get(5).BigInt() block.Difficulty = header.Get(5).BigInt()
block.Number = header.Get(6).BigInt() block.Number = header.Get(6).BigInt()
@ -323,7 +307,7 @@ func NewUncleBlockFromValue(header *ethutil.Value) *Block {
block.PrevHash = header.Get(0).Bytes() block.PrevHash = header.Get(0).Bytes()
block.UncleSha = header.Get(1).Bytes() block.UncleSha = header.Get(1).Bytes()
block.Coinbase = header.Get(2).Bytes() block.Coinbase = header.Get(2).Bytes()
block.state = ethstate.NewState(ethtrie.NewTrie(ethutil.Config.Db, header.Get(3).Val)) block.state = ethstate.NewState(ethtrie.New(ethutil.Config.Db, header.Get(3).Val))
block.TxSha = header.Get(4).Bytes() block.TxSha = header.Get(4).Bytes()
block.Difficulty = header.Get(5).BigInt() block.Difficulty = header.Get(5).BigInt()
block.Number = header.Get(6).BigInt() block.Number = header.Get(6).BigInt()

View File

@ -132,7 +132,7 @@ func (bc *BlockChain) FindCanonicalChain(blocks []*Block, commonBlockHash []byte
// Start with the newest block we got, all the way back to the common block we both know // Start with the newest block we got, all the way back to the common block we both know
for _, block := range blocks { for _, block := range blocks {
if bytes.Compare(block.Hash(), commonBlockHash) == 0 { if bytes.Compare(block.Hash(), commonBlockHash) == 0 {
chainlogger.Infoln("[CHAIN] We have found the common parent block, breaking") chainlogger.Infoln("We have found the common parent block, breaking")
break break
} }
chainDifficulty.Add(chainDifficulty, bc.CalculateBlockTD(block)) chainDifficulty.Add(chainDifficulty, bc.CalculateBlockTD(block))
@ -145,13 +145,13 @@ func (bc *BlockChain) FindCanonicalChain(blocks []*Block, commonBlockHash []byte
for i := 0; block != nil; block = bc.GetBlock(block.PrevHash) { for i := 0; block != nil; block = bc.GetBlock(block.PrevHash) {
i++ i++
if bytes.Compare(block.Hash(), commonBlockHash) == 0 { if bytes.Compare(block.Hash(), commonBlockHash) == 0 {
chainlogger.Infoln("We have found the common parent block, breaking") chainlogger.Infoln("Found the common parent block")
break break
} }
anOtherBlock := bc.GetBlock(block.PrevHash) anOtherBlock := bc.GetBlock(block.PrevHash)
if anOtherBlock == nil { if anOtherBlock == nil {
// We do not want to count the genesis block for difficulty since that's not being sent // We do not want to count the genesis block for difficulty since that's not being sent
chainlogger.Infoln("At genesis block, breaking") chainlogger.Infoln("Found genesis block. Stop")
break break
} }
curChainDifficulty.Add(curChainDifficulty, bc.CalculateBlockTD(block)) curChainDifficulty.Add(curChainDifficulty, bc.CalculateBlockTD(block))
@ -159,11 +159,11 @@ func (bc *BlockChain) FindCanonicalChain(blocks []*Block, commonBlockHash []byte
chainlogger.Infoln("Current chain difficulty:", curChainDifficulty) chainlogger.Infoln("Current chain difficulty:", curChainDifficulty)
if chainDifficulty.Cmp(curChainDifficulty) == 1 { if chainDifficulty.Cmp(curChainDifficulty) == 1 {
chainlogger.Infof("The incoming Chain beat our asses, resetting to block: %x", commonBlockHash) chainlogger.Infof("Resetting to block %x. Changing chain.")
bc.ResetTillBlockHash(commonBlockHash) bc.ResetTillBlockHash(commonBlockHash)
return false return false
} else { } else {
chainlogger.Infoln("Our chain showed the incoming chain who is boss. Ignoring.") chainlogger.Infoln("Current chain is longest chain. Ignoring incoming chain.")
return true return true
} }
} }

View File

@ -278,7 +278,7 @@ func MakeContract(tx *Transaction, state *ethstate.State) *ethstate.StateObject
contract := state.NewStateObject(addr) contract := state.NewStateObject(addr)
contract.InitCode = tx.Data contract.InitCode = tx.Data
contract.State = ethstate.NewState(ethtrie.NewTrie(ethutil.Config.Db, "")) contract.State = ethstate.NewState(ethtrie.New(ethutil.Config.Db, ""))
return contract return contract
} }

View File

@ -57,30 +57,12 @@ func (self *StateObject) Reset() {
self.State.Reset() self.State.Reset()
} }
/*
// Converts an transaction in to a state object
func MakeContract(tx *Transaction, state *State) *StateObject {
// Create contract if there's no recipient
if tx.IsContract() {
addr := tx.CreationAddress()
contract := state.NewStateObject(addr)
contract.initCode = tx.Data
contract.state = NewState(ethtrie.NewTrie(ethutil.Config.Db, ""))
return contract
}
return nil
}
*/
func NewStateObject(addr []byte) *StateObject { func NewStateObject(addr []byte) *StateObject {
// This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter. // This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter.
address := ethutil.Address(addr) address := ethutil.Address(addr)
object := &StateObject{address: address, Balance: new(big.Int), gasPool: new(big.Int)} object := &StateObject{address: address, Balance: new(big.Int), gasPool: new(big.Int)}
object.State = NewState(ethtrie.NewTrie(ethutil.Config.Db, "")) object.State = NewState(ethtrie.New(ethutil.Config.Db, ""))
object.storage = make(Storage) object.storage = make(Storage)
object.gasPool = new(big.Int) object.gasPool = new(big.Int)
@ -90,7 +72,7 @@ func NewStateObject(addr []byte) *StateObject {
func NewContract(address []byte, balance *big.Int, root []byte) *StateObject { func NewContract(address []byte, balance *big.Int, root []byte) *StateObject {
contract := NewStateObject(address) contract := NewStateObject(address)
contract.Balance = balance contract.Balance = balance
contract.State = NewState(ethtrie.NewTrie(ethutil.Config.Db, string(root))) contract.State = NewState(ethtrie.New(ethutil.Config.Db, string(root)))
return contract return contract
} }
@ -318,7 +300,7 @@ func (c *StateObject) RlpDecode(data []byte) {
c.Nonce = decoder.Get(0).Uint() c.Nonce = decoder.Get(0).Uint()
c.Balance = decoder.Get(1).BigInt() c.Balance = decoder.Get(1).BigInt()
c.State = NewState(ethtrie.NewTrie(ethutil.Config.Db, decoder.Get(2).Interface())) c.State = NewState(ethtrie.New(ethutil.Config.Db, decoder.Get(2).Interface()))
c.storage = make(map[string]*ethutil.Value) c.storage = make(map[string]*ethutil.Value)
c.gasPool = new(big.Int) c.gasPool = new(big.Int)

View File

@ -1,6 +1,6 @@
package ethtrie package ethtrie
import () import "math"
// Helper function for comparing slices // Helper function for comparing slices
func CompareIntSlice(a, b []int) bool { func CompareIntSlice(a, b []int) bool {
@ -17,9 +17,13 @@ func CompareIntSlice(a, b []int) bool {
// Returns the amount of nibbles that match each other from 0 ... // Returns the amount of nibbles that match each other from 0 ...
func MatchingNibbleLength(a, b []int) int { func MatchingNibbleLength(a, b []int) int {
i := 0 var i, length = 0, int(math.Min(float64(len(a)), float64(len(b))))
for CompareIntSlice(a[:i+1], b[:i+1]) && i < len(b) {
i += 1 for i < length {
if a[i] != b[i] {
break
}
i++
} }
return i return i

View File

@ -3,16 +3,17 @@ package ethtrie
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/ethereum/eth-go/ethcrypto"
"github.com/ethereum/eth-go/ethutil"
_ "reflect" _ "reflect"
"sync" "sync"
"github.com/ethereum/eth-go/ethcrypto"
"github.com/ethereum/eth-go/ethutil"
) )
func __ignore() { fmt.Println("") } func __ignore() { fmt.Println("") }
func ParanoiaCheck(t1 *Trie) (bool, *Trie) { func ParanoiaCheck(t1 *Trie) (bool, *Trie) {
t2 := NewTrie(ethutil.Config.Db, "") t2 := New(ethutil.Config.Db, "")
t1.NewIterator().Each(func(key string, v *ethutil.Value) { t1.NewIterator().Each(func(key string, v *ethutil.Value) {
t2.Update(key, v.Str()) t2.Update(key, v.Str())
@ -158,7 +159,7 @@ func copyRoot(root interface{}) interface{} {
return prevRootCopy return prevRootCopy
} }
func NewTrie(db ethutil.Database, Root interface{}) *Trie { func New(db ethutil.Database, Root interface{}) *Trie {
// Make absolute sure the root is copied // Make absolute sure the root is copied
r := copyRoot(Root) r := copyRoot(Root)
p := copyRoot(Root) p := copyRoot(Root)
@ -221,7 +222,7 @@ func (t *Trie) Cmp(trie *Trie) bool {
// Returns a copy of this trie // Returns a copy of this trie
func (t *Trie) Copy() *Trie { func (t *Trie) Copy() *Trie {
trie := NewTrie(t.cache.db, t.Root) trie := New(t.cache.db, t.Root)
for key, node := range t.cache.nodes { for key, node := range t.cache.nodes {
trie.cache.nodes[key] = node.Copy() trie.cache.nodes[key] = node.Copy()
} }

View File

@ -5,13 +5,14 @@ import (
_ "encoding/hex" _ "encoding/hex"
_ "encoding/json" _ "encoding/json"
"fmt" "fmt"
"github.com/ethereum/eth-go/ethutil"
_ "io/ioutil" _ "io/ioutil"
_ "math/rand" _ "math/rand"
_ "net/http" _ "net/http"
_ "reflect" _ "reflect"
"testing" "testing"
_ "time" _ "time"
"github.com/ethereum/eth-go/ethutil"
) )
const LONG_WORD = "1234567890abcdefghijklmnopqrstuvwxxzABCEFGHIJKLMNOPQRSTUVWXYZ" const LONG_WORD = "1234567890abcdefghijklmnopqrstuvwxxzABCEFGHIJKLMNOPQRSTUVWXYZ"
@ -38,14 +39,14 @@ func (db *MemDatabase) Print() {}
func (db *MemDatabase) Close() {} func (db *MemDatabase) Close() {}
func (db *MemDatabase) LastKnownTD() []byte { return nil } func (db *MemDatabase) LastKnownTD() []byte { return nil }
func New() (*MemDatabase, *Trie) { func NewTrie() (*MemDatabase, *Trie) {
db, _ := NewMemDatabase() db, _ := NewMemDatabase()
return db, NewTrie(db, "") return db, New(db, "")
} }
/* /*
func TestTrieSync(t *testing.T) { func TestTrieSync(t *testing.T) {
db, trie := New() db, trie := NewTrie()
trie.Update("dog", LONG_WORD) trie.Update("dog", LONG_WORD)
if len(db.db) != 0 { if len(db.db) != 0 {
@ -59,7 +60,7 @@ func TestTrieSync(t *testing.T) {
} }
func TestTrieDirtyTracking(t *testing.T) { func TestTrieDirtyTracking(t *testing.T) {
_, trie := New() _, trie := NewTrie()
trie.Update("dog", LONG_WORD) trie.Update("dog", LONG_WORD)
if !trie.cache.IsDirty { if !trie.cache.IsDirty {
t.Error("Expected trie to be dirty") t.Error("Expected trie to be dirty")
@ -79,7 +80,7 @@ func TestTrieDirtyTracking(t *testing.T) {
} }
func TestTrieReset(t *testing.T) { func TestTrieReset(t *testing.T) {
_, trie := New() _, trie := NewTrie()
trie.Update("cat", LONG_WORD) trie.Update("cat", LONG_WORD)
if len(trie.cache.nodes) == 0 { if len(trie.cache.nodes) == 0 {
@ -94,7 +95,7 @@ func TestTrieReset(t *testing.T) {
} }
func TestTrieGet(t *testing.T) { func TestTrieGet(t *testing.T) {
_, trie := New() _, trie := NewTrie()
trie.Update("cat", LONG_WORD) trie.Update("cat", LONG_WORD)
x := trie.Get("cat") x := trie.Get("cat")
@ -104,7 +105,7 @@ func TestTrieGet(t *testing.T) {
} }
func TestTrieUpdating(t *testing.T) { func TestTrieUpdating(t *testing.T) {
_, trie := New() _, trie := NewTrie()
trie.Update("cat", LONG_WORD) trie.Update("cat", LONG_WORD)
trie.Update("cat", LONG_WORD+"1") trie.Update("cat", LONG_WORD+"1")
x := trie.Get("cat") x := trie.Get("cat")
@ -114,8 +115,8 @@ func TestTrieUpdating(t *testing.T) {
} }
func TestTrieCmp(t *testing.T) { func TestTrieCmp(t *testing.T) {
_, trie1 := New() _, trie1 := NewTrie()
_, trie2 := New() _, trie2 := NewTrie()
trie1.Update("doge", LONG_WORD) trie1.Update("doge", LONG_WORD)
trie2.Update("doge", LONG_WORD) trie2.Update("doge", LONG_WORD)
@ -131,7 +132,7 @@ func TestTrieCmp(t *testing.T) {
} }
func TestTrieDelete(t *testing.T) { func TestTrieDelete(t *testing.T) {
_, trie := New() _, trie := NewTrie()
trie.Update("cat", LONG_WORD) trie.Update("cat", LONG_WORD)
exp := trie.Root exp := trie.Root
trie.Update("dog", LONG_WORD) trie.Update("dog", LONG_WORD)
@ -150,7 +151,7 @@ func TestTrieDelete(t *testing.T) {
} }
func TestTrieDeleteWithValue(t *testing.T) { func TestTrieDeleteWithValue(t *testing.T) {
_, trie := New() _, trie := NewTrie()
trie.Update("c", LONG_WORD) trie.Update("c", LONG_WORD)
exp := trie.Root exp := trie.Root
trie.Update("ca", LONG_WORD) trie.Update("ca", LONG_WORD)
@ -164,7 +165,7 @@ func TestTrieDeleteWithValue(t *testing.T) {
} }
func TestTriePurge(t *testing.T) { func TestTriePurge(t *testing.T) {
_, trie := New() _, trie := NewTrie()
trie.Update("c", LONG_WORD) trie.Update("c", LONG_WORD)
trie.Update("ca", LONG_WORD) trie.Update("ca", LONG_WORD)
trie.Update("cat", LONG_WORD) trie.Update("cat", LONG_WORD)
@ -248,7 +249,7 @@ func CreateTests(uri string, cb func(Test)) map[string]Test {
func TestRemote(t *testing.T) { func TestRemote(t *testing.T) {
CreateTests("https://raw.githubusercontent.com/ethereum/tests/develop/trietest.json", func(test Test) { CreateTests("https://raw.githubusercontent.com/ethereum/tests/develop/trietest.json", func(test Test) {
_, trie := New() _, trie := NewTrie()
for key, value := range test.In { for key, value := range test.In {
trie.Update(get(key), get(value)) trie.Update(get(key), get(value))
} }
@ -263,12 +264,12 @@ func TestRemote(t *testing.T) {
func TestTrieReplay(t *testing.T) { func TestTrieReplay(t *testing.T) {
CreateTests("https://raw.githubusercontent.com/ethereum/tests/develop/trietest.json", func(test Test) { CreateTests("https://raw.githubusercontent.com/ethereum/tests/develop/trietest.json", func(test Test) {
_, trie := New() _, trie := NewTrie()
for key, value := range test.In { for key, value := range test.In {
trie.Update(get(key), get(value)) trie.Update(get(key), get(value))
} }
_, trie2 := New() _, trie2 := NewTrie()
trie.NewIterator().Each(func(key string, v *ethutil.Value) { trie.NewIterator().Each(func(key string, v *ethutil.Value) {
trie2.Update(key, v.Str()) trie2.Update(key, v.Str())
}) })
@ -314,7 +315,7 @@ func TestRegression(t *testing.T) {
roots := make(map[string]int) roots := make(map[string]int)
for i := 0; i < MaxTest; i++ { for i := 0; i < MaxTest; i++ {
_, trie := New() _, trie := NewTrie()
data := RandomData() data := RandomData()
for _, test := range data { for _, test := range data {
@ -333,7 +334,7 @@ func TestRegression(t *testing.T) {
} }
func TestDelete(t *testing.T) { func TestDelete(t *testing.T) {
_, trie := New() _, trie := NewTrie()
trie.Update("a", "jeffreytestlongstring") trie.Update("a", "jeffreytestlongstring")
trie.Update("aa", "otherstring") trie.Update("aa", "otherstring")
@ -352,7 +353,7 @@ func TestDelete(t *testing.T) {
trie.Update("aaaa", "testmegood") trie.Update("aaaa", "testmegood")
fmt.Println("aa =>", trie.Get("aa")) fmt.Println("aa =>", trie.Get("aa"))
_, t2 := New() _, t2 := NewTrie()
trie.NewIterator().Each(func(key string, v *ethutil.Value) { trie.NewIterator().Each(func(key string, v *ethutil.Value) {
if key == "aaaa" { if key == "aaaa" {
t2.Update(key, v.Str()) t2.Update(key, v.Str())
@ -369,7 +370,7 @@ func TestDelete(t *testing.T) {
*/ */
func TestRndCase(t *testing.T) { func TestRndCase(t *testing.T) {
_, trie := New() _, trie := NewTrie()
data := []struct{ k, v string }{ data := []struct{ k, v string }{
{"0000000000000000000000000000000000000000000000000000000000000001", "a07573657264617461000000000000000000000000000000000000000000000000"}, {"0000000000000000000000000000000000000000000000000000000000000001", "a07573657264617461000000000000000000000000000000000000000000000000"},

View File

@ -2,14 +2,14 @@ package ethvm
import ( import (
"fmt" "fmt"
"github.com/ethereum/eth-go/ethdb"
"github.com/ethereum/eth-go/ethlog"
"github.com/ethereum/eth-go/ethstate"
"github.com/ethereum/eth-go/ethutil"
"log" "log"
"math/big" "math/big"
"os" "os"
"testing" "testing"
"github.com/ethereum/eth-go/ethlog"
"github.com/ethereum/eth-go/ethstate"
"github.com/ethereum/eth-go/ethutil"
) )
type TestEnv struct { type TestEnv struct {
@ -27,9 +27,7 @@ func (self TestEnv) State() *ethstate.State { return nil }
func TestVm(t *testing.T) { func TestVm(t *testing.T) {
ethlog.AddLogSystem(ethlog.NewStdLogSystem(os.Stdout, log.LstdFlags, ethlog.LogLevel(4))) ethlog.AddLogSystem(ethlog.NewStdLogSystem(os.Stdout, log.LstdFlags, ethlog.LogLevel(4)))
db, _ := ethdb.NewMemDatabase()
ethutil.ReadConfig(".ethtest", "/tmp/ethtest", "") ethutil.ReadConfig(".ethtest", "/tmp/ethtest", "")
ethutil.Config.Db = db
stateObject := ethstate.NewStateObject([]byte{'j', 'e', 'f', 'f'}) stateObject := ethstate.NewStateObject([]byte{'j', 'e', 'f', 'f'})
callerClosure := NewClosure(stateObject, stateObject, []byte{0x60, 0x01}, big.NewInt(1000000), big.NewInt(0)) callerClosure := NewClosure(stateObject, stateObject, []byte{0x60, 0x01}, big.NewInt(1000000), big.NewInt(0))