Skip to content

Commit

Permalink
merge
Browse files Browse the repository at this point in the history
  • Loading branch information
obscuren committed Dec 3, 2014
2 parents 64f35ba + 3d9a4e7 commit 6095eda
Show file tree
Hide file tree
Showing 20 changed files with 124 additions and 82 deletions.
55 changes: 29 additions & 26 deletions chain/block_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,13 +118,27 @@ func (sm *BlockManager) ChainManager() *ChainManager {
return sm.bc
}

func (sm *BlockManager) TransitionState(statedb *state.State, parent, block *types.Block) (receipts types.Receipts, err error) {
coinbase := statedb.GetOrNewStateObject(block.Coinbase)
coinbase.SetGasPool(block.CalcGasLimit(parent))

// Process the transactions on to current block
receipts, _, _, _, err = sm.ProcessTransactions(coinbase, statedb, block, parent, block.Transactions())
if err != nil {
return nil, err
}

return receipts, nil
}

func (self *BlockManager) ProcessTransactions(coinbase *state.StateObject, state *state.State, block, parent *types.Block, txs types.Transactions) (types.Receipts, types.Transactions, types.Transactions, types.Transactions, error) {
var (
receipts types.Receipts
handled, unhandled types.Transactions
erroneous types.Transactions
totalUsedGas = big.NewInt(0)
err error
cumulativeSum = new(big.Int)
)

done:
Expand Down Expand Up @@ -156,6 +170,7 @@ done:
}

txGas.Sub(txGas, st.gas)
cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice))

// Update the state with pending changes
state.Update(txGas)
Expand All @@ -176,6 +191,7 @@ done:
}
}

block.Reward = cumulativeSum
block.GasUsed = totalUsedGas

return receipts, handled, unhandled, erroneous, err
Expand All @@ -187,8 +203,7 @@ func (sm *BlockManager) Process(block *types.Block) (td *big.Int, msgs state.Mes
defer sm.mutex.Unlock()

if sm.bc.HasBlock(block.Hash()) {
fmt.Println("already having this block")
return nil, nil, nil
return nil, nil, &KnownBlockError{block.Number, block.Hash()}
}

if !sm.bc.HasBlock(block.PrevHash) {
Expand All @@ -214,7 +229,7 @@ func (sm *BlockManager) ProcessWithParent(block, parent *types.Block) (td *big.I
fmt.Printf("## %x %x ##\n", block.Hash(), block.Number)
}

_, err = sm.ApplyDiff(state, parent, block)
_, err = sm.TransitionState(state, parent, block)
if err != nil {
return
}
Expand All @@ -235,12 +250,10 @@ func (sm *BlockManager) ProcessWithParent(block, parent *types.Block) (td *big.I

// Block validation
if err = sm.ValidateBlock(block, parent); err != nil {
statelogger.Errorln("validating block:", err)
return
}

if err = sm.AccumelateRewards(state, block, parent); err != nil {
statelogger.Errorln("accumulating reward", err)
return
}

Expand Down Expand Up @@ -273,27 +286,13 @@ func (sm *BlockManager) ProcessWithParent(block, parent *types.Block) (td *big.I
sm.transState = state.Copy()

sm.eth.TxPool().RemoveSet(block.Transactions())
fmt.Println("TD", td)

return td, messages, nil
} else {
return nil, nil, errors.New("total diff failed")
}
}

func (sm *BlockManager) ApplyDiff(state *state.State, parent, block *types.Block) (receipts types.Receipts, err error) {
coinbase := state.GetOrNewStateObject(block.Coinbase)
coinbase.SetGasPool(block.CalcGasLimit(parent))

// Process the transactions on to current block
receipts, _, _, _, err = sm.ProcessTransactions(coinbase, state, block, parent, block.Transactions())
if err != nil {
return nil, err
}

return receipts, nil
}

func (sm *BlockManager) CalculateTD(block *types.Block) (*big.Int, bool) {
uncleDiff := new(big.Int)
for _, uncle := range block.Uncles {
Expand All @@ -309,9 +308,6 @@ func (sm *BlockManager) CalculateTD(block *types.Block) (*big.Int, bool) {
// is greater than the previous.
if td.Cmp(sm.bc.TD) > 0 {
return td, true

// Set the new total difficulty back to the block chain
//sm.bc.SetTotalDifficulty(td)
}

return nil, false
Expand Down Expand Up @@ -375,17 +371,25 @@ func (sm *BlockManager) AccumelateRewards(state *state.State, block, parent *typ
r := new(big.Int)
r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))

uncleAccount := state.GetAccount(uncle.Coinbase)
uncleAccount := statedb.GetAccount(uncle.Coinbase)
uncleAccount.AddAmount(r)

reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
}

// Get the account associated with the coinbase
account := state.GetAccount(block.Coinbase)
account := statedb.GetAccount(block.Coinbase)
// Reward amount of ether to the coinbase address
account.AddAmount(reward)

statedb.Manifest().AddMessage(&state.Message{
To: block.Coinbase, From: block.Coinbase,
Input: nil,
Origin: nil,
Block: block.Hash(), Timestamp: block.Time, Coinbase: block.Coinbase, Number: block.Number,
Value: new(big.Int).Add(reward, block.Reward),
})

return nil
}

Expand All @@ -403,8 +407,7 @@ func (sm *BlockManager) GetMessages(block *types.Block) (messages []*state.Messa

defer state.Reset()

sm.ApplyDiff(state, parent, block)

sm.TransitionState(state, parent, block)
sm.AccumelateRewards(state, block, parent)

return state.Manifest().Messages, nil
Expand Down
3 changes: 3 additions & 0 deletions chain/chain_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,9 @@ func (self *ChainManager) InsertChain(chain Blocks) error {
continue
}

chainlogger.Infof("block #%v process failed (%x)\n", block.Number, block.Hash()[:4])
chainlogger.Infoln(block)
chainlogger.Infoln(err)
return err
}

Expand Down
14 changes: 9 additions & 5 deletions chain/dagger.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,17 @@ func (pow *EasyPow) Verify(hash []byte, diff *big.Int, nonce []byte) bool {
d := append(hash, nonce...)
sha.Write(d)

v := ethutil.BigPow(2, 256)
ret := new(big.Int).Div(v, diff)
verification := new(big.Int).Div(ethutil.BigPow(2, 256), diff)
res := ethutil.U256(ethutil.BigD(sha.Sum(nil)))

res := new(big.Int)
res.SetBytes(sha.Sum(nil))
/*
fmt.Printf("hash w/o nonce %x\n", hash)
fmt.Printf("2**256 / %v = %v\n", diff, verification)
fmt.Printf("%v <= %v\n", res, verification)
fmt.Printf("vlen: %d rlen: %d\n", len(verification.Bytes()), len(res.Bytes()))
*/

return res.Cmp(ret) == -1
return res.Cmp(verification) <= 0
}

func (pow *EasyPow) SetHash(hash *big.Int) {
Expand Down
4 changes: 2 additions & 2 deletions chain/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,12 @@ func IsTDError(e error) bool {
}

type KnownBlockError struct {
number uint64
number *big.Int
hash []byte
}

func (self *KnownBlockError) Error() string {
return fmt.Sprintf("block %d already known (%x)", self.number, self.hash[0:4])
return fmt.Sprintf("block %v already known (%x)", self.number, self.hash[0:4])
}
func IsKnownBlockErr(e error) bool {
_, ok := e.(*KnownBlockError)
Expand Down
4 changes: 2 additions & 2 deletions chain/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ func (self *Filter) bloomFilter(block *types.Block) bool {
var fromIncluded, toIncluded bool
if len(self.from) > 0 {
for _, from := range self.from {
if types.BloomLookup(block.LogsBloom, from) {
if types.BloomLookup(block.LogsBloom, from) || bytes.Equal(block.Coinbase, from) {
fromIncluded = true
break
}
Expand All @@ -187,7 +187,7 @@ func (self *Filter) bloomFilter(block *types.Block) bool {

if len(self.to) > 0 {
for _, to := range self.to {
if types.BloomLookup(block.LogsBloom, ethutil.U256(new(big.Int).Add(ethutil.Big1, ethutil.BigD(to))).Bytes()) {
if types.BloomLookup(block.LogsBloom, ethutil.U256(new(big.Int).Add(ethutil.Big1, ethutil.BigD(to))).Bytes()) || bytes.Equal(block.Coinbase, to) {
toIncluded = true
break
}
Expand Down
6 changes: 0 additions & 6 deletions chain/state_transition.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,12 +169,6 @@ func (self *StateTransition) TransitionState() (err error) {
return
}

//dataPrice := big.NewInt(int64(len(self.data)))
//dataPrice.Mul(dataPrice, vm.GasData)
//if err = self.UseGas(dataPrice); err != nil {
// return
//}

if sender.Balance().Cmp(self.value) < 0 {
return fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", self.value, sender.Balance)
}
Expand Down
2 changes: 2 additions & 0 deletions chain/types/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ type Block struct {
receipts Receipts
TxSha, ReceiptSha []byte
LogsBloom []byte

Reward *big.Int
}

func NewBlockFromBytes(raw []byte) *Block {
Expand Down
4 changes: 2 additions & 2 deletions chain/types/bloom9.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ import (
func CreateBloom(receipts Receipts) []byte {
bin := new(big.Int)
for _, receipt := range receipts {
bin.Or(bin, logsBloom(receipt.logs))
bin.Or(bin, LogsBloom(receipt.logs))
}

return ethutil.LeftPadBytes(bin.Bytes(), 64)
}

func logsBloom(logs state.Logs) *big.Int {
func LogsBloom(logs state.Logs) *big.Int {
bin := new(big.Int)
for _, log := range logs {
data := [][]byte{log.Address}
Expand Down
2 changes: 1 addition & 1 deletion cmd/ethereum/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import (

const (
ClientIdentifier = "Ethereum(G)"
Version = "0.7.6"
Version = "0.7.7"
)

var clilogger = logger.NewLogger("CLI")
Expand Down
2 changes: 2 additions & 0 deletions cmd/mist/assets/qml/views/miner.qml
Original file line number Diff line number Diff line change
Expand Up @@ -119,12 +119,14 @@ Rectangle {
}
}
Component.onCompleted: {
/*
// XXX Temp. replace with above eventually
var tmpItems = ["JEVCoin", "Some coin", "Other coin", "Etc coin"];
var address = "e6716f9544a56c530d868e4bfbacb172315bdead";
for (var i = 0; i < tmpItems.length; i++) {
mergedMiningModel.append({checked: false, name: tmpItems[i], address: address, id: 0, itemId: i});
}
*/
}
}
}
Expand Down
12 changes: 9 additions & 3 deletions cmd/mist/assets/qml/views/wallet.qml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@ Rectangle {
anchors.fill: parent

function onReady() {
menuItem.secondaryTitle = eth.numberToHuman(eth.balanceAt(eth.key().address))
setBalance()
}

function setBalance() {
balance.text = "<b>Balance</b>: " + eth.numberToHuman(eth.balanceAt(eth.key().address))
if(menuItem)
menuItem.secondaryTitle = eth.numberToHuman(eth.balanceAt(eth.key().address))
}

ListModel {
Expand All @@ -39,7 +45,6 @@ Rectangle {

Text {
id: balance
text: "<b>Balance</b>: " + eth.numberToHuman(eth.balanceAt(eth.key().address))
font.pixelSize: 24
anchors {
horizontalCenter: parent.horizontalCenter
Expand Down Expand Up @@ -126,7 +131,6 @@ Rectangle {
var value = txValue.text + denomModel.get(valueDenom.currentIndex).zeros;
var gasPrice = "10000000000000"
var res = eth.transact({from: eth.key().privateKey, to: txTo.text, value: value, gas: "500", gasPrice: gasPrice})
console.log(res)
}
}
}
Expand Down Expand Up @@ -158,6 +162,8 @@ Rectangle {
}

function addTxs(messages) {
setBalance()

for(var i = 0; i < messages.length; i++) {
var message = messages.get(i);
var to = eth.lookupName(message.to);
Expand Down
2 changes: 1 addition & 1 deletion cmd/mist/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import (

const (
ClientIdentifier = "Mist"
Version = "0.7.6"
Version = "0.7.7"
)

var ethereum *eth.Ethereum
Expand Down
2 changes: 1 addition & 1 deletion cmd/utils/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ func BlockDo(ethereum *eth.Ethereum, hash []byte) error {

parent := ethereum.ChainManager().GetBlock(block.PrevHash)

_, err := ethereum.BlockManager().ApplyDiff(parent.State(), parent, block)
_, err := ethereum.BlockManager().TransitionState(parent.State(), parent, block)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const (
// The size of the output buffer for writing messages
outputBufferSize = 50
// Current protocol version
ProtocolVersion = 45
ProtocolVersion = 46
// Current P2P version
P2PVersion = 2
// Ethereum network version
Expand Down
17 changes: 11 additions & 6 deletions tests/helper/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ type Env struct {
time int64
difficulty *big.Int
gasLimit *big.Int

logs state.Logs
}

func NewEnv(state *state.State) *Env {
Expand Down Expand Up @@ -51,24 +53,27 @@ func (self *Env) Difficulty() *big.Int { return self.difficulty }
func (self *Env) BlockHash() []byte { return nil }
func (self *Env) State() *state.State { return self.state }
func (self *Env) GasLimit() *big.Int { return self.gasLimit }
func (self *Env) AddLog(*state.Log) {}
func (self *Env) AddLog(log *state.Log) {
self.logs = append(self.logs, log)
}
func (self *Env) Transfer(from, to vm.Account, amount *big.Int) error {
return vm.Transfer(from, to, amount)
}

func RunVm(state *state.State, env, exec map[string]string) ([]byte, *big.Int, error) {
func RunVm(state *state.State, env, exec map[string]string) ([]byte, state.Logs, *big.Int, error) {
address := FromHex(exec["address"])
caller := state.GetOrNewStateObject(FromHex(exec["caller"]))

evm := vm.New(NewEnvFromMap(state, env, exec), vm.DebugVmTy)
vmenv := NewEnvFromMap(state, env, exec)
evm := vm.New(vmenv, vm.DebugVmTy)
execution := vm.NewExecution(evm, address, FromHex(exec["data"]), ethutil.Big(exec["gas"]), ethutil.Big(exec["gasPrice"]), ethutil.Big(exec["value"]))
execution.SkipTransfer = true
ret, err := execution.Exec(address, caller)

return ret, execution.Gas, err
return ret, vmenv.logs, execution.Gas, err
}

func RunState(state *state.State, env, tx map[string]string) ([]byte, *big.Int, error) {
func RunState(state *state.State, env, tx map[string]string) ([]byte, state.Logs, *big.Int, error) {
address := FromHex(tx["to"])
keyPair, _ := crypto.NewKeyPairFromSec([]byte(ethutil.Hex2Bytes(tx["secretKey"])))
caller := state.GetOrNewStateObject(keyPair.Address())
Expand All @@ -79,5 +84,5 @@ func RunState(state *state.State, env, tx map[string]string) ([]byte, *big.Int,
execution := vm.NewExecution(evm, address, FromHex(tx["data"]), ethutil.Big(tx["gasLimit"]), ethutil.Big(tx["gasPrice"]), ethutil.Big(tx["value"]))
ret, err := execution.Exec(address, caller)

return ret, execution.Gas, err
return ret, vmenv.logs, execution.Gas, err
}
Loading

0 comments on commit 6095eda

Please sign in to comment.