Refactored ethutil.Config.Db out

This commit is contained in:
obscuren 2015-01-07 13:17:48 +01:00
parent 032ab66529
commit fed3e6a808
35 changed files with 125 additions and 493 deletions

View File

@ -31,6 +31,7 @@ import (
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/state"
)
const (
@ -103,7 +104,8 @@ func main() {
}
// Leave the Println. This needs clean output for piping
fmt.Printf("%s\n", block.State().Dump())
statedb := state.New(block.Root(), ethereum.Db())
fmt.Printf("%s\n", statedb.Dump())
fmt.Println(block)

View File

@ -29,6 +29,7 @@ import (
"os"
"strings"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/tests/helper"
@ -41,8 +42,8 @@ type Account struct {
Storage map[string]string
}
func StateObjectFromAccount(addr string, account Account) *state.StateObject {
obj := state.NewStateObject(ethutil.Hex2Bytes(addr))
func StateObjectFromAccount(db ethutil.Database, addr string, account Account) *state.StateObject {
obj := state.NewStateObject(ethutil.Hex2Bytes(addr), db)
obj.SetBalance(ethutil.Big(account.Balance))
if ethutil.IsHex(account.Code) {
@ -74,9 +75,10 @@ func RunVmTest(js string) (failed int) {
}
for name, test := range tests {
state := state.New(helper.NewTrie())
db, _ := ethdb.NewMemDatabase()
state := state.New(nil, db)
for addr, account := range test.Pre {
obj := StateObjectFromAccount(addr, account)
obj := StateObjectFromAccount(db, addr, account)
state.SetStateObject(obj)
}

View File

@ -35,7 +35,6 @@ import (
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/ptrie"
"github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/vm"
)
@ -63,7 +62,7 @@ func main() {
ethutil.ReadConfig("/tmp/evmtest", "/tmp/evm", "")
db, _ := ethdb.NewMemDatabase()
statedb := state.New(ptrie.New(nil, db))
statedb := state.New(nil, db)
sender := statedb.NewStateObject([]byte("sender"))
receiver := statedb.NewStateObject([]byte("receiver"))
//receiver.SetCode([]byte(*code))

View File

@ -29,6 +29,7 @@ import (
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/state"
)
type plugin struct {
@ -121,7 +122,7 @@ func (self *Gui) DumpState(hash, path string) {
return
}
stateDump = block.State().Dump()
stateDump = state.New(block.Root(), self.eth.Db()).Dump()
}
file, err := os.OpenFile(path[7:], os.O_CREATE|os.O_RDWR, os.ModePerm)

View File

@ -117,18 +117,7 @@ func (gui *Gui) Start(assetPath string) {
context.SetVar("eth", gui.uiLib)
context.SetVar("shh", gui.whisper)
// Load the main QML interface
data, _ := ethutil.Config.Db.Get([]byte("KeyRing"))
var win *qml.Window
var err error
var addlog = false
if len(data) == 0 {
win, err = gui.showKeyImport(context)
} else {
win, err = gui.showWallet(context)
addlog = true
}
win, err := gui.showWallet(context)
if err != nil {
guilogger.Errorln("asset not found: you can set an alternative asset path on the command line using option 'asset_path'", err)
@ -139,9 +128,7 @@ func (gui *Gui) Start(assetPath string) {
win.Show()
// only add the gui guilogger after window is shown otherwise slider wont be shown
if addlog {
logger.AddLogSystem(gui)
}
logger.AddLogSystem(gui)
win.Wait()
// need to silence gui guilogger after window closed otherwise logsystem hangs (but do not save loglevel)
@ -275,7 +262,7 @@ func (gui *Gui) insertTransaction(window string, tx *types.Transaction) {
}
var (
ptx = xeth.NewJSTx(tx, gui.xeth.World().State())
ptx = xeth.NewJSTx(tx)
send = nameReg.Storage(tx.From())
rec = nameReg.Storage(tx.To())
s, r string

View File

@ -39,6 +39,7 @@ import (
"github.com/ethereum/go-ethereum/miner"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc"
"github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/xeth"
)
@ -259,7 +260,8 @@ func BlockDo(ethereum *eth.Ethereum, hash []byte) error {
parent := ethereum.ChainManager().GetBlock(block.ParentHash())
_, err := ethereum.BlockProcessor().TransitionState(parent.State(), parent, block)
statedb := state.New(parent.Root(), ethereum.Db())
_, err := ethereum.BlockProcessor().TransitionState(statedb, parent, block)
if err != nil {
return err
}

View File

@ -36,6 +36,7 @@ type EthManager interface {
}
type BlockProcessor struct {
db ethutil.Database
// Mutex for locking the block processor. Blocks can only be handled one at a time
mutex sync.Mutex
// Canonical block chain
@ -57,8 +58,9 @@ type BlockProcessor struct {
eventMux *event.TypeMux
}
func NewBlockProcessor(txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
func NewBlockProcessor(db ethutil.Database, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
sm := &BlockProcessor{
db: db,
mem: make(map[string]*big.Int),
Pow: ezp.New(),
bc: chainManager,
@ -170,7 +172,8 @@ func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, msgs state.M
func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big.Int, messages state.Messages, err error) {
sm.lastAttemptedBlock = block
state := state.New(parent.Trie().Copy())
state := state.New(parent.Root(), sm.db)
//state := state.New(parent.Trie().Copy())
// Block validation
if err = sm.ValidateBlock(block, parent); err != nil {
@ -352,7 +355,8 @@ func (sm *BlockProcessor) GetMessages(block *types.Block) (messages []*state.Mes
var (
parent = sm.bc.GetBlock(block.Header().ParentHash)
state = state.New(parent.Trie().Copy())
//state = state.New(parent.Trie().Copy())
state = state.New(parent.Root(), sm.db)
)
defer state.Reset()

View File

@ -55,6 +55,7 @@ func CalcGasLimit(parent, block *types.Block) *big.Int {
type ChainManager struct {
//eth EthManager
db ethutil.Database
processor types.BlockProcessor
eventMux *event.TypeMux
genesisBlock *types.Block
@ -96,13 +97,9 @@ func (self *ChainManager) CurrentBlock() *types.Block {
return self.currentBlock
}
func NewChainManager(mux *event.TypeMux) *ChainManager {
bc := &ChainManager{}
bc.genesisBlock = GenesisBlock()
bc.eventMux = mux
func NewChainManager(db ethutil.Database, mux *event.TypeMux) *ChainManager {
bc := &ChainManager{db: db, genesisBlock: GenesisBlock(db), eventMux: mux}
bc.setLastBlock()
bc.transState = bc.State().Copy()
return bc
@ -120,7 +117,7 @@ func (self *ChainManager) SetProcessor(proc types.BlockProcessor) {
}
func (self *ChainManager) State() *state.StateDB {
return state.New(self.CurrentBlock().Trie())
return state.New(self.CurrentBlock().Root(), self.db)
}
func (self *ChainManager) TransState() *state.StateDB {
@ -128,7 +125,7 @@ func (self *ChainManager) TransState() *state.StateDB {
}
func (bc *ChainManager) setLastBlock() {
data, _ := ethutil.Config.Db.Get([]byte("LastBlock"))
data, _ := bc.db.Get([]byte("LastBlock"))
if len(data) != 0 {
var block types.Block
rlp.Decode(bytes.NewReader(data), &block)
@ -137,7 +134,7 @@ func (bc *ChainManager) setLastBlock() {
bc.lastBlockNumber = block.Header().Number.Uint64()
// Set the last know difficulty (might be 0x0 as initial value, Genesis)
bc.td = ethutil.BigD(ethutil.Config.Db.LastKnownTD())
bc.td = ethutil.BigD(bc.db.LastKnownTD())
} else {
bc.Reset()
}
@ -183,7 +180,7 @@ func (bc *ChainManager) Reset() {
defer bc.mu.Unlock()
for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {
ethutil.Config.Db.Delete(block.Hash())
bc.db.Delete(block.Hash())
}
// Prepare the genesis block
@ -210,7 +207,7 @@ func (self *ChainManager) Export() []byte {
func (bc *ChainManager) insert(block *types.Block) {
encodedBlock := ethutil.Encode(block)
ethutil.Config.Db.Put([]byte("LastBlock"), encodedBlock)
bc.db.Put([]byte("LastBlock"), encodedBlock)
bc.currentBlock = block
bc.lastBlockHash = block.Hash()
}
@ -219,7 +216,7 @@ func (bc *ChainManager) write(block *types.Block) {
bc.writeBlockInfo(block)
encodedBlock := ethutil.Encode(block)
ethutil.Config.Db.Put(block.Hash(), encodedBlock)
bc.db.Put(block.Hash(), encodedBlock)
}
// Accessors
@ -229,7 +226,7 @@ func (bc *ChainManager) Genesis() *types.Block {
// Block fetching methods
func (bc *ChainManager) HasBlock(hash []byte) bool {
data, _ := ethutil.Config.Db.Get(hash)
data, _ := bc.db.Get(hash)
return len(data) != 0
}
@ -254,7 +251,7 @@ func (self *ChainManager) GetBlockHashesFromHash(hash []byte, max uint64) (chain
}
func (self *ChainManager) GetBlock(hash []byte) *types.Block {
data, _ := ethutil.Config.Db.Get(hash)
data, _ := self.db.Get(hash)
if len(data) == 0 {
return nil
}
@ -286,7 +283,7 @@ func (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {
}
func (bc *ChainManager) setTotalDifficulty(td *big.Int) {
ethutil.Config.Db.Put([]byte("LTD"), td.Bytes())
bc.db.Put([]byte("LTD"), td.Bytes())
bc.td = td
}
@ -348,7 +345,7 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error {
self.setTotalDifficulty(td)
self.insert(block)
self.transState = state.New(cblock.Trie().Copy())
self.transState = state.New(cblock.Root(), self.db) //state.New(cblock.Trie().Copy())
}
}

View File

@ -21,14 +21,6 @@ func init() {
ethutil.ReadConfig("/tmp/ethtest", "/tmp/ethtest", "ETH")
}
func reset() {
db, err := ethdb.NewMemDatabase()
if err != nil {
panic("Could not create mem-db, failing")
}
ethutil.Config.Db = db
}
func loadChain(fn string, t *testing.T) (types.Blocks, error) {
fh, err := os.OpenFile(path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "_data", fn), os.O_RDONLY, os.ModePerm)
if err != nil {
@ -54,7 +46,7 @@ func insertChain(done chan bool, chainMan *ChainManager, chain types.Blocks, t *
}
func TestChainInsertions(t *testing.T) {
reset()
db, _ := ethdb.NewMemDatabase()
chain1, err := loadChain("valid1", t)
if err != nil {
@ -69,9 +61,9 @@ func TestChainInsertions(t *testing.T) {
}
var eventMux event.TypeMux
chainMan := NewChainManager(&eventMux)
chainMan := NewChainManager(db, &eventMux)
txPool := NewTxPool(&eventMux)
blockMan := NewBlockProcessor(txPool, chainMan, &eventMux)
blockMan := NewBlockProcessor(db, txPool, chainMan, &eventMux)
chainMan.SetProcessor(blockMan)
const max = 2
@ -94,7 +86,7 @@ func TestChainInsertions(t *testing.T) {
}
func TestChainMultipleInsertions(t *testing.T) {
reset()
db, _ := ethdb.NewMemDatabase()
const max = 4
chains := make([]types.Blocks, max)
@ -113,9 +105,9 @@ func TestChainMultipleInsertions(t *testing.T) {
}
}
var eventMux event.TypeMux
chainMan := NewChainManager(&eventMux)
chainMan := NewChainManager(db, &eventMux)
txPool := NewTxPool(&eventMux)
blockMan := NewBlockProcessor(txPool, chainMan, &eventMux)
blockMan := NewBlockProcessor(db, txPool, chainMan, &eventMux)
chainMan.SetProcessor(blockMan)
done := make(chan bool, max)
for i, chain := range chains {

View File

@ -19,7 +19,7 @@ var ZeroHash512 = make([]byte, 64)
var EmptyShaList = crypto.Sha3(ethutil.Encode([]interface{}{}))
var EmptyListRoot = crypto.Sha3(ethutil.Encode(""))
func GenesisBlock() *types.Block {
func GenesisBlock(db ethutil.Database) *types.Block {
genesis := types.NewBlock(ZeroHash256, ZeroHash160, nil, big.NewInt(131072), crypto.Sha3(big.NewInt(42).Bytes()), "")
genesis.Header().Number = ethutil.Big0
genesis.Header().GasLimit = big.NewInt(1000000)
@ -30,7 +30,8 @@ func GenesisBlock() *types.Block {
genesis.SetTransactions(types.Transactions{})
genesis.SetReceipts(types.Receipts{})
statedb := state.New(genesis.Trie())
statedb := state.New(genesis.Root(), db)
//statedb := state.New(genesis.Trie())
for _, addr := range []string{
"51ba59315b3a95761d0863b05ccc7a7f54703d99",
"e4157b34ea9615cfbde6b4fda419828124b70c78",

View File

@ -77,7 +77,6 @@ func NewTestManager() *TestManager {
fmt.Println("Could not create mem-db, failing")
return nil
}
ethutil.Config.Db = db
testManager := &TestManager{}
testManager.eventMux = new(event.TypeMux)

View File

@ -6,16 +6,22 @@ import (
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/state"
)
// State query interface
type stateQuery struct{}
type stateQuery struct{ db ethutil.Database }
func SQ() stateQuery {
db, _ := ethdb.NewMemDatabase()
return stateQuery{db: db}
}
func (self stateQuery) GetAccount(addr []byte) *state.StateObject {
return state.NewStateObject(addr)
return state.NewStateObject(addr, self.db)
}
func transaction() *types.Transaction {
@ -66,7 +72,7 @@ func TestRemoveInvalid(t *testing.T) {
pool, key := setup()
tx1 := transaction()
pool.addTx(tx1)
pool.RemoveInvalid(stateQuery{})
pool.RemoveInvalid(SQ())
if pool.Size() > 0 {
t.Error("expected pool size to be 0")
}
@ -74,7 +80,7 @@ func TestRemoveInvalid(t *testing.T) {
tx1.SetNonce(1)
tx1.SignECDSA(key)
pool.addTx(tx1)
pool.RemoveInvalid(stateQuery{})
pool.RemoveInvalid(SQ())
if pool.Size() != 1 {
t.Error("expected pool size to be 1, is", pool.Size())
}

View File

@ -9,9 +9,7 @@ import (
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/ptrie"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/state"
)
type Header struct {
@ -168,16 +166,18 @@ func (self *Block) RlpDataForStorage() interface{} {
}
// Header accessors (add as you need them)
func (self *Block) Number() *big.Int { return self.header.Number }
func (self *Block) NumberU64() uint64 { return self.header.Number.Uint64() }
func (self *Block) Bloom() []byte { return self.header.Bloom }
func (self *Block) Coinbase() []byte { return self.header.Coinbase }
func (self *Block) Time() int64 { return int64(self.header.Time) }
func (self *Block) GasLimit() *big.Int { return self.header.GasLimit }
func (self *Block) GasUsed() *big.Int { return self.header.GasUsed }
func (self *Block) Trie() *ptrie.Trie { return ptrie.New(self.header.Root, ethutil.Config.Db) }
func (self *Block) Number() *big.Int { return self.header.Number }
func (self *Block) NumberU64() uint64 { return self.header.Number.Uint64() }
func (self *Block) Bloom() []byte { return self.header.Bloom }
func (self *Block) Coinbase() []byte { return self.header.Coinbase }
func (self *Block) Time() int64 { return int64(self.header.Time) }
func (self *Block) GasLimit() *big.Int { return self.header.GasLimit }
func (self *Block) GasUsed() *big.Int { return self.header.GasUsed }
//func (self *Block) Trie() *ptrie.Trie { return ptrie.New(self.header.Root, ethutil.Config.Db) }
//func (self *Block) State() *state.StateDB { return state.New(self.Trie()) }
func (self *Block) Root() []byte { return self.header.Root }
func (self *Block) SetRoot(root []byte) { self.header.Root = root }
func (self *Block) State() *state.StateDB { return state.New(self.Trie()) }
func (self *Block) Size() ethutil.StorageSize { return ethutil.StorageSize(len(ethutil.Encode(self))) }
// Implement pow.Block

View File

@ -1,6 +1,7 @@
package types
import (
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/ptrie"
)
@ -11,7 +12,8 @@ type DerivableList interface {
}
func DeriveSha(list DerivableList) []byte {
trie := ptrie.New(nil, ethutil.Config.Db)
db, _ := ethdb.NewMemDatabase()
trie := ptrie.New(nil, db)
for i := 0; i < list.Len(); i++ {
trie.Update(ethutil.Encode(i), list.GetRlp(i))
}

View File

@ -81,7 +81,7 @@ type Ethereum struct {
func New(config *Config) (*Ethereum, error) {
// Boostrap database
logger := ethlogger.New(config.DataDir, config.LogFile, config.LogLevel)
db, err := ethdb.NewLDBDatabase("database")
db, err := ethdb.NewLDBDatabase("blockchain")
if err != nil {
return nil, err
}
@ -110,7 +110,7 @@ func New(config *Config) (*Ethereum, error) {
clientId := p2p.NewSimpleClientIdentity(config.Name, config.Version, config.Identifier, keyManager.PublicKey())
saveProtocolVersion(db)
ethutil.Config.Db = db
//ethutil.Config.Db = db
eth := &Ethereum{
shutdownChan: make(chan bool),
@ -123,9 +123,9 @@ func New(config *Config) (*Ethereum, error) {
logger: logger,
}
eth.chainManager = core.NewChainManager(eth.EventMux())
eth.chainManager = core.NewChainManager(db, eth.EventMux())
eth.txPool = core.NewTxPool(eth.EventMux())
eth.blockProcessor = core.NewBlockProcessor(eth.txPool, eth.chainManager, eth.EventMux())
eth.blockProcessor = core.NewBlockProcessor(db, eth.txPool, eth.chainManager, eth.EventMux())
eth.chainManager.SetProcessor(eth.blockProcessor)
eth.whisper = whisper.New()

View File

@ -10,8 +10,6 @@ import (
// Config struct
type ConfigManager struct {
Db Database
ExecPath string
Debug bool
Diff bool

View File

@ -129,10 +129,9 @@ func (self *JSRE) initStdFuncs() {
*/
func (self *JSRE) dump(call otto.FunctionCall) otto.Value {
var state *state.StateDB
var block *types.Block
if len(call.ArgumentList) > 0 {
var block *types.Block
if call.Argument(0).IsNumber() {
num, _ := call.Argument(0).ToInteger()
block = self.ethereum.ChainManager().GetBlockByNumber(uint64(num))
@ -149,12 +148,12 @@ func (self *JSRE) dump(call otto.FunctionCall) otto.Value {
return otto.UndefinedValue()
}
state = block.State()
} else {
state = self.ethereum.ChainManager().State()
block = self.ethereum.ChainManager().CurrentBlock()
}
v, _ := self.Vm.ToValue(state.Dump())
statedb := state.New(block.Root(), self.ethereum.Db())
v, _ := self.Vm.ToValue(statedb.Dump())
return v
}

View File

@ -31,6 +31,7 @@ import (
"github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/pow"
"github.com/ethereum/go-ethereum/pow/ezp"
"github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
@ -178,6 +179,7 @@ func (self *Miner) mine() {
blockProcessor = self.eth.BlockProcessor()
chainMan = self.eth.ChainManager()
block = chainMan.NewBlock(self.Coinbase)
state = state.New(block.Root(), self.eth.Db())
)
block.Header().Extra = self.Extra
@ -187,13 +189,11 @@ func (self *Miner) mine() {
}
parent := chainMan.GetBlock(block.ParentHash())
coinbase := block.State().GetOrNewStateObject(block.Coinbase())
coinbase := state.GetOrNewStateObject(block.Coinbase())
coinbase.SetGasPool(core.CalcGasLimit(parent, block))
transactions := self.finiliseTxs()
state := block.State()
// Accumulate all valid transactions and apply them to the new state
// Error may be ignored. It's not important during mining
receipts, txs, _, erroneous, err := blockProcessor.ApplyTransactions(coinbase, state, block, transactions, true)

View File

@ -1,12 +0,0 @@
package ar
import (
"math/big"
"github.com/ethereum/go-ethereum/trie"
)
type Block interface {
Trie() *trie.Trie
Diff() *big.Int
}

View File

@ -1,54 +0,0 @@
package ar
import "math/big"
const lenops int64 = 9
type OpsFunc func(a, b *big.Int) *big.Int
var ops [lenops]OpsFunc
func init() {
ops[0] = Add
ops[1] = Mul
ops[2] = Mod
ops[3] = Xor
ops[4] = And
ops[5] = Or
ops[6] = Sub1
ops[7] = XorSub
ops[8] = Rsh
}
func Add(x, y *big.Int) *big.Int {
return new(big.Int).Add(x, y)
}
func Mul(x, y *big.Int) *big.Int {
return new(big.Int).Mul(x, y)
}
func Mod(x, y *big.Int) *big.Int {
return new(big.Int).Mod(x, y)
}
func Xor(x, y *big.Int) *big.Int {
return new(big.Int).Xor(x, y)
}
func And(x, y *big.Int) *big.Int {
return new(big.Int).And(x, y)
}
func Or(x, y *big.Int) *big.Int {
return new(big.Int).Or(x, y)
}
func Sub1(x, y *big.Int) *big.Int {
a := big.NewInt(-1)
a.Sub(a, x)
return a
}
func XorSub(x, y *big.Int) *big.Int {
t := Sub1(x, nil)
return t.Xor(t, y)
}
func Rsh(x, y *big.Int) *big.Int {
return new(big.Int).Rsh(x, uint(y.Uint64()%64))
}

View File

@ -1,122 +0,0 @@
package ar
import (
"math/big"
"github.com/ethereum/go-ethereum/ethutil"
)
type Entry struct {
op OpsFunc
i, j *big.Int
}
type Tape struct {
tape []Entry
block Block
}
func NewTape(block Block) *Tape {
return &Tape{nil, block}
}
func (self *Tape) gen(w, h int64, gen NumberGenerator) {
self.tape = nil
for v := int64(0); v < h; v++ {
op := ops[gen.rand64(lenops).Int64()]
r := gen.rand64(100).Uint64()
var j *big.Int
if r < 20 && v > 20 {
j = self.tape[len(self.tape)-1].i
} else {
j = gen.rand64(w)
}
i := gen.rand64(w)
self.tape = append(self.tape, Entry{op, i, j})
}
}
func (self *Tape) runTape(w, h int64, gen NumberGenerator) *big.Int {
var mem []*big.Int
for i := int64(0); i < w; i++ {
mem = append(mem, gen.rand(ethutil.BigPow(2, 64)))
}
set := func(i, j int) Entry {
entry := self.tape[i*100+j]
mem[entry.i.Uint64()] = entry.op(entry.i, entry.j)
return entry
}
dir := true
for i := 0; i < int(h)/100; i++ {
var entry Entry
if dir {
for j := 0; j < 100; j++ {
entry = set(i, j)
}
} else {
for j := 99; i >= 0; j-- {
entry = set(i, j)
}
}
t := mem[entry.i.Uint64()]
if big.NewInt(2).Cmp(new(big.Int).Mod(t, big.NewInt(37))) < 0 {
dir = !dir
}
}
return Sha3(mem)
}
func (self *Tape) Verify(header, nonce []byte) bool {
n := ethutil.BigD(nonce)
var w int64 = 10000
var h int64 = 150000
gen := Rnd(Sha3([]interface{}{header, new(big.Int).Div(n, big.NewInt(1000))}))
self.gen(w, h, gen)
gen = Rnd(Sha3([]interface{}{header, new(big.Int).Mod(n, big.NewInt(1000))}))
hash := self.runTape(w, h, gen)
it := self.block.Trie().Iterator()
next := it.Next(string(new(big.Int).Mod(hash, ethutil.BigPow(2, 160)).Bytes()))
req := ethutil.BigPow(2, 256)
req.Div(req, self.block.Diff())
return Sha3([]interface{}{hash, next}).Cmp(req) < 0
}
func (self *Tape) Run(header []byte) []byte {
nonce := big.NewInt(0)
var w int64 = 10000
var h int64 = 150000
req := ethutil.BigPow(2, 256)
req.Div(req, self.block.Diff())
for {
if new(big.Int).Mod(nonce, b(1000)).Cmp(b(0)) == 0 {
gen := Rnd(Sha3([]interface{}{header, new(big.Int).Div(nonce, big.NewInt(1000))}))
self.gen(w, h, gen)
}
gen := Rnd(Sha3([]interface{}{header, new(big.Int).Mod(nonce, big.NewInt(1000))}))
hash := self.runTape(w, h, gen)
it := self.block.Trie().Iterator()
next := it.Next(string(new(big.Int).Mod(hash, ethutil.BigPow(2, 160)).Bytes()))
if Sha3([]interface{}{hash, next}).Cmp(req) < 0 {
return nonce.Bytes()
} else {
nonce.Add(nonce, ethutil.Big1)
}
}
}

View File

@ -1,47 +0,0 @@
package ar
import (
"fmt"
"math/big"
"testing"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/trie"
)
type TestBlock struct {
trie *trie.Trie
}
func NewTestBlock() *TestBlock {
db, _ := ethdb.NewMemDatabase()
return &TestBlock{
trie: trie.New(db, ""),
}
}
func (self *TestBlock) Diff() *big.Int {
return b(10)
}
func (self *TestBlock) Trie() *trie.Trie {
return self.trie
}
func (self *TestBlock) Hash() []byte {
a := make([]byte, 32)
a[0] = 10
a[1] = 2
return a
}
func TestPow(t *testing.T) {
entry := make([]byte, 32)
entry[0] = 255
block := NewTestBlock()
pow := NewTape(block)
nonce := pow.Run(block.Hash())
fmt.Println("Found nonce", nonce)
}

View File

@ -1,66 +0,0 @@
package ar
import (
"math/big"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethutil"
)
var b = big.NewInt
type Node interface {
Big() *big.Int
}
type ByteNode []byte
func (self ByteNode) Big() *big.Int {
return ethutil.BigD(ethutil.Encode([]byte(self)))
}
func Sha3(v interface{}) *big.Int {
if b, ok := v.(*big.Int); ok {
return ethutil.BigD(crypto.Sha3(b.Bytes()))
} else if b, ok := v.([]interface{}); ok {
return ethutil.BigD(crypto.Sha3(ethutil.Encode(b)))
} else if s, ok := v.([]*big.Int); ok {
v := make([]interface{}, len(s))
for i, b := range s {
v[i] = b
}
return ethutil.BigD(crypto.Sha3(ethutil.Encode(v)))
}
return nil
}
type NumberGenerator interface {
rand(r *big.Int) *big.Int
rand64(r int64) *big.Int
}
type rnd struct {
seed *big.Int
}
func Rnd(s *big.Int) rnd {
return rnd{s}
}
func (self rnd) rand(r *big.Int) *big.Int {
o := b(0).Mod(self.seed, r)
self.seed.Div(self.seed, r)
if self.seed.Cmp(ethutil.BigPow(2, 64)) < 0 {
self.seed = Sha3(self.seed)
}
return o
}
func (self rnd) rand64(r int64) *big.Int {
return self.rand(b(r))
}

View File

@ -28,7 +28,7 @@ func (self *StateDB) Dump() []byte {
it := self.trie.Iterator()
for it.Next() {
stateObject := NewStateObjectFromBytes(it.Key, it.Value)
stateObject := NewStateObjectFromBytes(it.Key, it.Value, self.db)
account := Account{Balance: stateObject.balance.String(), Nonce: stateObject.Nonce, Root: ethutil.Bytes2Hex(stateObject.Root()), CodeHash: ethutil.Bytes2Hex(stateObject.codeHash)}
account.Storage = make(map[string]string)

View File

@ -28,6 +28,7 @@ func (self Storage) Copy() Storage {
}
type StateObject struct {
db ethutil.Database
// Address of the object
address []byte
// Shared attributes
@ -57,28 +58,20 @@ func (self *StateObject) Reset() {
self.State.Reset()
}
func NewStateObject(addr []byte) *StateObject {
func NewStateObject(addr []byte, db ethutil.Database) *StateObject {
// This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter.
address := ethutil.Address(addr)
object := &StateObject{address: address, balance: new(big.Int), gasPool: new(big.Int)}
object.State = New(ptrie.New(nil, ethutil.Config.Db)) //New(trie.New(ethutil.Config.Db, ""))
object := &StateObject{db: db, address: address, balance: new(big.Int), gasPool: new(big.Int)}
object.State = New(nil, db) //New(trie.New(ethutil.Config.Db, ""))
object.storage = make(Storage)
object.gasPool = new(big.Int)
return object
}
func NewContract(address []byte, balance *big.Int, root []byte) *StateObject {
contract := NewStateObject(address)
contract.balance = balance
contract.State = New(ptrie.New(nil, ethutil.Config.Db)) //New(trie.New(ethutil.Config.Db, string(root)))
return contract
}
func NewStateObjectFromBytes(address, data []byte) *StateObject {
object := &StateObject{address: address}
func NewStateObjectFromBytes(address, data []byte, db ethutil.Database) *StateObject {
object := &StateObject{address: address, db: db}
object.RlpDecode(data)
return object
@ -242,7 +235,7 @@ func (self *StateObject) RefundGas(gas, price *big.Int) {
}
func (self *StateObject) Copy() *StateObject {
stateObject := NewStateObject(self.Address())
stateObject := NewStateObject(self.Address(), self.db)
stateObject.balance.Set(self.balance)
stateObject.codeHash = ethutil.CopyBytes(self.codeHash)
stateObject.Nonce = self.Nonce
@ -310,13 +303,13 @@ func (c *StateObject) RlpDecode(data []byte) {
c.Nonce = decoder.Get(0).Uint()
c.balance = decoder.Get(1).BigInt()
c.State = New(ptrie.New(decoder.Get(2).Bytes(), ethutil.Config.Db)) //New(trie.New(ethutil.Config.Db, decoder.Get(2).Interface()))
c.State = New(decoder.Get(2).Bytes(), c.db) //New(trie.New(ethutil.Config.Db, decoder.Get(2).Interface()))
c.storage = make(map[string]*ethutil.Value)
c.gasPool = new(big.Int)
c.codeHash = decoder.Get(3).Bytes()
c.Code, _ = ethutil.Config.Db.Get(c.codeHash)
c.Code, _ = c.db.Get(c.codeHash)
}
// Storage change object. Used by the manifest for notifying changes to

View File

@ -5,7 +5,6 @@ import (
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/ptrie"
)
type StateSuite struct {
@ -25,10 +24,9 @@ func (s *StateSuite) TestDump(c *checker.C) {
}
func (s *StateSuite) SetUpTest(c *checker.C) {
db, _ := ethdb.NewMemDatabase()
ethutil.ReadConfig(".ethtest", "/tmp/ethtest", "")
ethutil.Config.Db = db
s.state = New(ptrie.New(nil, db))
db, _ := ethdb.NewMemDatabase()
s.state = New(nil, db)
}
func (s *StateSuite) TestSnapshot(c *checker.C) {

View File

@ -17,7 +17,7 @@ var statelogger = logger.NewLogger("STATE")
// * Contracts
// * Accounts
type StateDB struct {
//Trie *trie.Trie
db ethutil.Database
trie *ptrie.Trie
stateObjects map[string]*StateObject
@ -30,8 +30,10 @@ type StateDB struct {
}
// Create a new state from a given trie
func New(trie *ptrie.Trie) *StateDB {
return &StateDB{trie: trie, stateObjects: make(map[string]*StateObject), manifest: NewManifest(), refund: make(map[string]*big.Int)}
//func New(trie *ptrie.Trie) *StateDB {
func New(root []byte, db ethutil.Database) *StateDB {
trie := ptrie.New(root, db)
return &StateDB{db: db, trie: trie, stateObjects: make(map[string]*StateObject), manifest: NewManifest(), refund: make(map[string]*big.Int)}
}
func (self *StateDB) EmptyLogs() {
@ -138,7 +140,7 @@ func (self *StateDB) UpdateStateObject(stateObject *StateObject) {
addr := stateObject.Address()
if len(stateObject.CodeHash()) > 0 {
ethutil.Config.Db.Put(stateObject.CodeHash(), stateObject.Code)
self.db.Put(stateObject.CodeHash(), stateObject.Code)
}
self.trie.Update(addr, stateObject.RlpEncode())
@ -165,7 +167,7 @@ func (self *StateDB) GetStateObject(addr []byte) *StateObject {
return nil
}
stateObject = NewStateObjectFromBytes(addr, []byte(data))
stateObject = NewStateObjectFromBytes(addr, []byte(data), self.db)
self.SetStateObject(stateObject)
return stateObject
@ -191,7 +193,7 @@ func (self *StateDB) NewStateObject(addr []byte) *StateObject {
statelogger.Debugf("(+) %x\n", addr)
stateObject := NewStateObject(addr)
stateObject := NewStateObject(addr, self.db)
self.stateObjects[string(addr)] = stateObject
return stateObject
@ -212,7 +214,8 @@ func (s *StateDB) Cmp(other *StateDB) bool {
func (self *StateDB) Copy() *StateDB {
if self.trie != nil {
state := New(self.trie.Copy())
state := New(nil, self.db)
state.trie = self.trie.Copy()
for k, stateObject := range self.stateObjects {
state.stateObjects[k] = stateObject.Copy()
}
@ -305,7 +308,7 @@ func (self *StateDB) Update(gasUsed *big.Int) {
// FIXME trie delete is broken
if deleted {
valid, t2 := ptrie.ParanoiaCheck(self.trie, ethutil.Config.Db)
valid, t2 := ptrie.ParanoiaCheck(self.trie, self.db)
if !valid {
statelogger.Infof("Warn: PARANOIA: Different state root during copy %x vs %x\n", self.trie.Root(), t2.Root())

View File

@ -16,5 +16,4 @@ func init() {
logpkg.AddLogSystem(Logger)
ethutil.ReadConfig(".ethtest", "/tmp/ethtest", "")
ethutil.Config.Db, _ = NewMemDatabase()
}

View File

@ -7,6 +7,7 @@ import (
"testing"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/state"
@ -38,8 +39,8 @@ func (self Log) Topics() [][]byte {
return t
}
func StateObjectFromAccount(addr string, account Account) *state.StateObject {
obj := state.NewStateObject(ethutil.Hex2Bytes(addr))
func StateObjectFromAccount(db ethutil.Database, addr string, account Account) *state.StateObject {
obj := state.NewStateObject(ethutil.Hex2Bytes(addr), db)
obj.SetBalance(ethutil.Big(account.Balance))
if ethutil.IsHex(account.Code) {
@ -84,9 +85,10 @@ func RunVmTest(p string, t *testing.T) {
continue
}
*/
statedb := state.New(helper.NewTrie())
db, _ := ethdb.NewMemDatabase()
statedb := state.New(nil, db)
for addr, account := range test.Pre {
obj := StateObjectFromAccount(addr, account)
obj := StateObjectFromAccount(db, addr, account)
statedb.SetStateObject(obj)
for a, v := range account.Storage {
obj.SetState(helper.FromHex(a), ethutil.NewValue(helper.FromHex(v)))

View File

@ -1,5 +1,6 @@
package trie
/*
import (
"bytes"
@ -141,3 +142,4 @@ func (self *Iterator) Next(key string) []byte {
return self.Key
}
*/

View File

@ -1,5 +1,6 @@
package trie
/*
import (
"bytes"
"fmt"
@ -174,11 +175,9 @@ func New(db ethutil.Database, Root interface{}) *Trie {
func (self *Trie) setRoot(root interface{}) {
switch t := root.(type) {
case string:
/*
if t == "" {
root = crypto.Sha3(ethutil.Encode(""))
}
*/
//if t == "" {
// root = crypto.Sha3(ethutil.Encode(""))
//}
self.Root = []byte(t)
case []byte:
self.Root = root
@ -187,10 +186,6 @@ func (self *Trie) setRoot(root interface{}) {
}
}
/*
* Public (query) interface functions
*/
func (t *Trie) Update(key, value string) {
t.mut.Lock()
defer t.mut.Unlock()
@ -629,3 +624,4 @@ func (it *TrieIterator) iterateNode(key []byte, currentNode *ethutil.Value, cb E
}
}
}
*/

View File

@ -1,5 +1,6 @@
package trie
/*
import (
"bytes"
"encoding/hex"
@ -337,59 +338,6 @@ func (s *TrieSuite) TestItems(c *checker.C) {
c.Assert(s.trie.GetRoot(), checker.DeepEquals, ethutil.Hex2Bytes(exp))
}
/*
func TestRndCase(t *testing.T) {
_, trie := NewTrie()
data := []struct{ k, v string }{
{"0000000000000000000000000000000000000000000000000000000000000001", "a07573657264617461000000000000000000000000000000000000000000000000"},
{"0000000000000000000000000000000000000000000000000000000000000003", "8453bb5b31"},
{"0000000000000000000000000000000000000000000000000000000000000004", "850218711a00"},
{"0000000000000000000000000000000000000000000000000000000000000005", "9462d7705bd0b3ecbc51a8026a25597cb28a650c79"},
{"0000000000000000000000000000000000000000000000000000000000000010", "947e70f9460402290a3e487dae01f610a1a8218fda"},
{"0000000000000000000000000000000000000000000000000000000000000111", "01"},
{"0000000000000000000000000000000000000000000000000000000000000112", "a053656e6174650000000000000000000000000000000000000000000000000000"},
{"0000000000000000000000000000000000000000000000000000000000000113", "a053656e6174650000000000000000000000000000000000000000000000000000"},
{"53656e6174650000000000000000000000000000000000000000000000000000", "94977e3f62f5e1ed7953697430303a3cfa2b5b736e"},
}
for _, e := range data {
trie.Update(string(ethutil.Hex2Bytes(e.k)), string(ethutil.Hex2Bytes(e.v)))
}
fmt.Printf("root after update %x\n", trie.Root)
trie.NewIterator().Each(func(k string, v *ethutil.Value) {
fmt.Printf("%x %x\n", k, v.Bytes())
})
data = []struct{ k, v string }{
{"0000000000000000000000000000000000000000000000000000000000000112", ""},
{"436974697a656e73000000000000000000000000000000000000000000000001", ""},
{"436f757274000000000000000000000000000000000000000000000000000002", ""},
{"53656e6174650000000000000000000000000000000000000000000000000000", ""},
{"436f757274000000000000000000000000000000000000000000000000000000", ""},
{"53656e6174650000000000000000000000000000000000000000000000000001", ""},
{"0000000000000000000000000000000000000000000000000000000000000113", ""},
{"436974697a656e73000000000000000000000000000000000000000000000000", ""},
{"436974697a656e73000000000000000000000000000000000000000000000002", ""},
{"436f757274000000000000000000000000000000000000000000000000000001", ""},
{"0000000000000000000000000000000000000000000000000000000000000111", ""},
{"53656e6174650000000000000000000000000000000000000000000000000002", ""},
}
for _, e := range data {
trie.Delete(string(ethutil.Hex2Bytes(e.k)))
}
fmt.Printf("root after delete %x\n", trie.Root)
trie.NewIterator().Each(func(k string, v *ethutil.Value) {
fmt.Printf("%x %x\n", k, v.Bytes())
})
fmt.Printf("%x\n", trie.Get(string(ethutil.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))))
}
*/
func TestOtherSomething(t *testing.T) {
_, trie := NewTrie()
@ -445,3 +393,4 @@ func BenchmarkUpdate(b *testing.B) {
trie.Update(fmt.Sprintf("aaaaaaaaaaaaaaa%d", i), "value")
}
}
*/

View File

@ -39,7 +39,7 @@ func NewJSBlock(block *types.Block) *JSBlock {
ptxs := make([]*JSTransaction, len(block.Transactions()))
for i, tx := range block.Transactions() {
ptxs[i] = NewJSTx(tx, block.State())
ptxs[i] = NewJSTx(tx)
}
txlist := ethutil.NewList(ptxs)
@ -76,7 +76,7 @@ func (self *JSBlock) GetTransaction(hash string) *JSTransaction {
return nil
}
return NewJSTx(tx, self.ref.State())
return NewJSTx(tx)
}
type JSTransaction struct {
@ -95,7 +95,7 @@ type JSTransaction struct {
Confirmations int `json:"confirmations"`
}
func NewJSTx(tx *types.Transaction, state *state.StateDB) *JSTransaction {
func NewJSTx(tx *types.Transaction) *JSTransaction {
hash := ethutil.Bytes2Hex(tx.Hash())
receiver := ethutil.Bytes2Hex(tx.To())
if receiver == "0000000000000000000000000000000000000000" {

View File

@ -36,7 +36,7 @@ func (self *World) SafeGet(addr []byte) *Object {
func (self *World) safeGet(addr []byte) *state.StateObject {
object := self.State().GetStateObject(addr)
if object == nil {
object = state.NewStateObject(addr)
object = state.NewStateObject(addr, self.pipe.obj.Db())
}
return object

View File

@ -81,7 +81,7 @@ func (self *XEth) Execute(addr []byte, data []byte, value, gas, price *ethutil.V
func (self *XEth) ExecuteObject(object *Object, data []byte, value, gas, price *ethutil.Value) ([]byte, error) {
var (
initiator = state.NewStateObject(self.obj.KeyManager().KeyPair().Address())
initiator = state.NewStateObject(self.obj.KeyManager().KeyPair().Address(), self.obj.Db())
block = self.chainManager.CurrentBlock()
)