conversions. -compilable-

pull/532/head
obscuren 10 years ago
parent 942980609f
commit 0a1eeca41e
  1. 4
      cmd/ethereum/admin.go
  2. 2
      cmd/ethereum/main.go
  3. 6
      core/state_transition.go
  4. 10
      eth/backend.go
  5. 61
      eth/protocol.go
  6. 3
      miner/miner.go
  7. 27
      miner/worker.go
  8. 19
      rpc/api.go
  9. 77
      rpc/responses.go
  10. 4
      rpc/util.go
  11. 6
      xeth/types.go
  12. 50
      xeth/xeth.go

@ -8,8 +8,8 @@ import (
"time" "time"
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
@ -239,7 +239,7 @@ func (js *jsre) dumpBlock(call otto.FunctionCall) otto.Value {
block = js.ethereum.ChainManager().GetBlockByNumber(uint64(num)) block = js.ethereum.ChainManager().GetBlockByNumber(uint64(num))
} else if call.Argument(0).IsString() { } else if call.Argument(0).IsString() {
hash, _ := call.Argument(0).ToString() hash, _ := call.Argument(0).ToString()
block = js.ethereum.ChainManager().GetBlock(common.Hex2Bytes(hash)) block = js.ethereum.ChainManager().GetBlock(common.HexToHash(hash))
} else { } else {
fmt.Println("invalid argument for dump. Either hex string or number") fmt.Println("invalid argument for dump. Either hex string or number")
} }

@ -302,7 +302,7 @@ func dump(ctx *cli.Context) {
for _, arg := range ctx.Args() { for _, arg := range ctx.Args() {
var block *types.Block var block *types.Block
if hashish(arg) { if hashish(arg) {
block = chainmgr.GetBlock(common.Hex2Bytes(arg)) block = chainmgr.GetBlock(common.HexToHash(arg))
} else { } else {
num, _ := strconv.Atoi(arg) num, _ := strconv.Atoi(arg)
block = chainmgr.GetBlockByNumber(uint64(num)) block = chainmgr.GetBlockByNumber(uint64(num))

@ -57,6 +57,12 @@ type Message interface {
Data() []byte Data() []byte
} }
func AddressFromMessage(msg Message) common.Address {
from, _ := msg.From()
return crypto.CreateAddress(from, msg.Nonce())
}
func MessageCreatesContract(msg Message) bool { func MessageCreatesContract(msg Message) bool {
return msg.To() == nil return msg.To() == nil
} }

@ -10,11 +10,11 @@ import (
"github.com/ethereum/ethash" "github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/blockpool" "github.com/ethereum/go-ethereum/blockpool"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/miner" "github.com/ethereum/go-ethereum/miner"
@ -288,7 +288,7 @@ func (s *Ethereum) StartMining() error {
servlogger.Errorf("Cannot start mining without coinbase: %v\n", err) servlogger.Errorf("Cannot start mining without coinbase: %v\n", err)
return fmt.Errorf("no coinbase: %v", err) return fmt.Errorf("no coinbase: %v", err)
} }
s.miner.Start(cb) s.miner.Start(common.BytesToAddress(cb))
return nil return nil
} }
@ -304,9 +304,9 @@ func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
func (s *Ethereum) BlockPool() *blockpool.BlockPool { return s.blockPool } func (s *Ethereum) BlockPool() *blockpool.BlockPool { return s.blockPool }
func (s *Ethereum) Whisper() *whisper.Whisper { return s.whisper } func (s *Ethereum) Whisper() *whisper.Whisper { return s.whisper }
func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux } func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
func (s *Ethereum) BlockDb() common.Database { return s.blockDb } func (s *Ethereum) BlockDb() common.Database { return s.blockDb }
func (s *Ethereum) StateDb() common.Database { return s.stateDb } func (s *Ethereum) StateDb() common.Database { return s.stateDb }
func (s *Ethereum) ExtraDb() common.Database { return s.extraDb } func (s *Ethereum) ExtraDb() common.Database { return s.extraDb }
func (s *Ethereum) IsListening() bool { return true } // Always listening func (s *Ethereum) IsListening() bool { return true } // Always listening
func (s *Ethereum) PeerCount() int { return s.net.PeerCount() } func (s *Ethereum) PeerCount() int { return s.net.PeerCount() }
func (s *Ethereum) PeerInfo() int { return s.net.PeerCount() } func (s *Ethereum) PeerInfo() int { return s.net.PeerCount() }

@ -1,13 +1,12 @@
package eth package eth
import ( import (
"bytes"
"fmt" "fmt"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/errs" "github.com/ethereum/go-ethereum/errs"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
@ -76,15 +75,15 @@ type txPool interface {
} }
type chainManager interface { type chainManager interface {
GetBlockHashesFromHash(hash []byte, amount uint64) (hashes [][]byte) GetBlockHashesFromHash(hash common.Hash, amount uint64) (hashes []common.Hash)
GetBlock(hash []byte) (block *types.Block) GetBlock(hash common.Hash) (block *types.Block)
Status() (td *big.Int, currentBlock []byte, genesisBlock []byte) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash)
} }
type blockPool interface { type blockPool interface {
AddBlockHashes(next func() ([]byte, bool), peerId string) AddBlockHashes(next func() (common.Hash, bool), peerId string)
AddBlock(block *types.Block, peerId string) AddBlock(block *types.Block, peerId string)
AddPeer(td *big.Int, currentBlock []byte, peerId string, requestHashes func([]byte) error, requestBlocks func([][]byte) error, peerError func(*errs.Error)) (best bool) AddPeer(td *big.Int, currentBlock common.Hash, peerId string, requestHashes func(common.Hash) error, requestBlocks func([]common.Hash) error, peerError func(*errs.Error)) (best bool)
RemovePeer(peerId string) RemovePeer(peerId string)
} }
@ -95,7 +94,7 @@ type newBlockMsgData struct {
} }
type getBlockHashesMsgData struct { type getBlockHashesMsgData struct {
Hash []byte Hash common.Hash
Amount uint64 Amount uint64
} }
@ -167,7 +166,7 @@ func (self *ethProtocol) handle() error {
} }
for _, tx := range txs { for _, tx := range txs {
jsonlogger.LogJson(&logger.EthTxReceived{ jsonlogger.LogJson(&logger.EthTxReceived{
TxHash: common.Bytes2Hex(tx.Hash()), TxHash: tx.Hash().Hex(),
RemoteId: self.peer.ID().String(), RemoteId: self.peer.ID().String(),
}) })
} }
@ -183,7 +182,7 @@ func (self *ethProtocol) handle() error {
request.Amount = maxHashes request.Amount = maxHashes
} }
hashes := self.chainManager.GetBlockHashesFromHash(request.Hash, request.Amount) hashes := self.chainManager.GetBlockHashesFromHash(request.Hash, request.Amount)
return p2p.EncodeMsg(self.rw, BlockHashesMsg, common.ByteSliceToInterface(hashes)...) return p2p.EncodeMsg(self.rw, BlockHashesMsg, rlp.Flat(hashes))
case BlockHashesMsg: case BlockHashesMsg:
msgStream := rlp.NewStream(msg.Payload) msgStream := rlp.NewStream(msg.Payload)
@ -192,14 +191,16 @@ func (self *ethProtocol) handle() error {
} }
var i int var i int
iter := func() (hash []byte, ok bool) { iter := func() (hash common.Hash, ok bool) {
hash, err := msgStream.Bytes() var h common.Hash
err := msgStream.Decode(&h)
if err == rlp.EOL { if err == rlp.EOL {
return nil, false return common.Hash{}, false
} else if err != nil { } else if err != nil {
self.protoError(ErrDecode, "msg %v: after %v hashes : %v", msg, i, err) self.protoError(ErrDecode, "msg %v: after %v hashes : %v", msg, i, err)
return nil, false return common.Hash{}, false
} }
i++ i++
return hash, true return hash, true
} }
@ -215,14 +216,14 @@ func (self *ethProtocol) handle() error {
var i int var i int
for { for {
i++ i++
var hash []byte var hash common.Hash
if err := msgStream.Decode(&hash); err != nil { err := msgStream.Decode(&hash)
if err == rlp.EOL { if err == rlp.EOL {
break break
} else { } else {
return self.protoError(ErrDecode, "msg %v: %v", msg, err) return self.protoError(ErrDecode, "msg %v: %v", msg, err)
}
} }
block := self.chainManager.GetBlock(hash) block := self.chainManager.GetBlock(hash)
if block != nil { if block != nil {
blocks = append(blocks, block) blocks = append(blocks, block)
@ -259,10 +260,10 @@ func (self *ethProtocol) handle() error {
_, chainHead, _ := self.chainManager.Status() _, chainHead, _ := self.chainManager.Status()
jsonlogger.LogJson(&logger.EthChainReceivedNewBlock{ jsonlogger.LogJson(&logger.EthChainReceivedNewBlock{
BlockHash: common.Bytes2Hex(hash), BlockHash: hash.Hex(),
BlockNumber: request.Block.Number(), // this surely must be zero BlockNumber: request.Block.Number(), // this surely must be zero
ChainHeadHash: common.Bytes2Hex(chainHead), ChainHeadHash: chainHead.Hex(),
BlockPrevHash: common.Bytes2Hex(request.Block.ParentHash()), BlockPrevHash: request.Block.ParentHash().Hex(),
RemoteId: self.peer.ID().String(), RemoteId: self.peer.ID().String(),
}) })
// to simplify backend interface adding a new block // to simplify backend interface adding a new block
@ -282,8 +283,8 @@ type statusMsgData struct {
ProtocolVersion uint32 ProtocolVersion uint32
NetworkId uint32 NetworkId uint32
TD *big.Int TD *big.Int
CurrentBlock []byte CurrentBlock common.Hash
GenesisBlock []byte GenesisBlock common.Hash
} }
func (self *ethProtocol) statusMsg() p2p.Msg { func (self *ethProtocol) statusMsg() p2p.Msg {
@ -325,7 +326,7 @@ func (self *ethProtocol) handleStatus() error {
_, _, genesisBlock := self.chainManager.Status() _, _, genesisBlock := self.chainManager.Status()
if !bytes.Equal(status.GenesisBlock, genesisBlock) { if status.GenesisBlock != genesisBlock {
return self.protoError(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock, genesisBlock) return self.protoError(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock, genesisBlock)
} }
@ -344,14 +345,14 @@ func (self *ethProtocol) handleStatus() error {
return nil return nil
} }
func (self *ethProtocol) requestBlockHashes(from []byte) error { func (self *ethProtocol) requestBlockHashes(from common.Hash) error {
self.peer.Debugf("fetching hashes (%d) %x...\n", maxHashes, from[0:4]) self.peer.Debugf("fetching hashes (%d) %x...\n", maxHashes, from[0:4])
return p2p.EncodeMsg(self.rw, GetBlockHashesMsg, interface{}(from), uint64(maxHashes)) return p2p.EncodeMsg(self.rw, GetBlockHashesMsg, interface{}(from), uint64(maxHashes))
} }
func (self *ethProtocol) requestBlocks(hashes [][]byte) error { func (self *ethProtocol) requestBlocks(hashes []common.Hash) error {
self.peer.Debugf("fetching %v blocks", len(hashes)) self.peer.Debugf("fetching %v blocks", len(hashes))
return p2p.EncodeMsg(self.rw, GetBlocksMsg, common.ByteSliceToInterface(hashes)...) return p2p.EncodeMsg(self.rw, GetBlocksMsg, rlp.Flat(hashes))
} }
func (self *ethProtocol) protoError(code int, format string, params ...interface{}) (err *errs.Error) { func (self *ethProtocol) protoError(code int, format string, params ...interface{}) (err *errs.Error) {

@ -4,6 +4,7 @@ import (
"math/big" "math/big"
"github.com/ethereum/ethash" "github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/pow" "github.com/ethereum/go-ethereum/pow"
@ -32,7 +33,7 @@ func (self *Miner) Mining() bool {
return self.mining return self.mining
} }
func (self *Miner) Start(coinbase []byte) { func (self *Miner) Start(coinbase common.Address) {
self.mining = true self.mining = true
self.worker = newWorker(coinbase, self.eth) self.worker = newWorker(coinbase, self.eth)
self.worker.register(NewCpuMiner(0, self.pow)) self.worker.register(NewCpuMiner(0, self.pow))

@ -7,9 +7,9 @@ import (
"sync" "sync"
"time" "time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/pow" "github.com/ethereum/go-ethereum/pow"
@ -39,7 +39,7 @@ func env(block *types.Block, eth core.Backend) *environment {
coinbase: state.GetOrNewStateObject(block.Coinbase()), coinbase: state.GetOrNewStateObject(block.Coinbase()),
} }
for _, ancestor := range eth.ChainManager().GetAncestors(block, 7) { for _, ancestor := range eth.ChainManager().GetAncestors(block, 7) {
env.ancestors.Add(string(ancestor.Hash())) env.ancestors.Add(ancestor.Hash())
} }
return env return env
@ -71,14 +71,14 @@ type worker struct {
eth core.Backend eth core.Backend
chain *core.ChainManager chain *core.ChainManager
proc *core.BlockProcessor proc *core.BlockProcessor
coinbase []byte coinbase common.Address
current *environment current *environment
mining bool mining bool
} }
func newWorker(coinbase []byte, eth core.Backend) *worker { func newWorker(coinbase common.Address, eth core.Backend) *worker {
return &worker{ return &worker{
eth: eth, eth: eth,
mux: eth.EventMux(), mux: eth.EventMux(),
@ -152,13 +152,13 @@ func (self *worker) wait() {
block := self.current.block block := self.current.block
if block.Number().Uint64() == work.Number && block.Nonce() == 0 { if block.Number().Uint64() == work.Number && block.Nonce() == 0 {
self.current.block.SetNonce(work.Nonce) self.current.block.SetNonce(work.Nonce)
self.current.block.Header().MixDigest = work.MixDigest self.current.block.Header().MixDigest = common.BytesToHash(work.MixDigest)
jsonlogger.LogJson(&logger.EthMinerNewBlock{ jsonlogger.LogJson(&logger.EthMinerNewBlock{
BlockHash: common.Bytes2Hex(block.Hash()), BlockHash: block.Hash().Hex(),
BlockNumber: block.Number(), BlockNumber: block.Number(),
ChainHeadHash: common.Bytes2Hex(block.ParentHeaderHash), ChainHeadHash: block.ParentHeaderHash.Hex(),
BlockPrevHash: common.Bytes2Hex(block.ParentHeaderHash), BlockPrevHash: block.ParentHeaderHash.Hex(),
}) })
if err := self.chain.InsertChain(types.Blocks{self.current.block}); err == nil { if err := self.chain.InsertChain(types.Blocks{self.current.block}); err == nil {
@ -208,9 +208,10 @@ gasLimit:
fallthrough fallthrough
case core.IsInvalidTxErr(err): case core.IsInvalidTxErr(err):
// Remove invalid transactions // Remove invalid transactions
self.chain.TxState().RemoveNonce(tx.From(), tx.Nonce()) from, _ := tx.From()
self.chain.TxState().RemoveNonce(from, tx.Nonce())
remove = append(remove, tx) remove = append(remove, tx)
minerlogger.Infof("TX (%x) failed. Transaction will be removed\n", tx.Hash()[:4]) minerlogger.Infof("TX (%x) failed. Transaction will be removed\n", tx.Hash().Bytes()[:4])
case state.IsGasLimitErr(err): case state.IsGasLimitErr(err):
minerlogger.Infof("Gas limit reached for block. %d TXs included in this block\n", i) minerlogger.Infof("Gas limit reached for block. %d TXs included in this block\n", i)
// Break on gas limit // Break on gas limit
@ -232,13 +233,13 @@ var (
) )
func (self *worker) commitUncle(uncle *types.Header) error { func (self *worker) commitUncle(uncle *types.Header) error {
if self.current.uncles.Has(string(uncle.Hash())) { if self.current.uncles.Has(uncle.Hash()) {
// Error not unique // Error not unique
return core.UncleError("Uncle not unique") return core.UncleError("Uncle not unique")
} }
self.current.uncles.Add(string(uncle.Hash())) self.current.uncles.Add(uncle.Hash())
if !self.current.ancestors.Has(string(uncle.ParentHash)) { if !self.current.ancestors.Has(uncle.ParentHash) {
return core.UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4])) return core.UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
} }

@ -668,7 +668,7 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error
return NewValidationError("Index", "does not exist") return NewValidationError("Index", "does not exist")
} }
uncle, err := p.GetBlockByHash(toHex(v.Uncles[args.Index]), false) uncle, err := p.GetBlockByHash(v.Uncles[args.Index].Hex(), false)
if err != nil { if err != nil {
return err return err
} }
@ -687,7 +687,7 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error
return NewValidationError("Index", "does not exist") return NewValidationError("Index", "does not exist")
} }
uncle, err := p.GetBlockByHash(toHex(v.Uncles[args.Index]), false) uncle, err := p.GetBlockByHash(v.Uncles[args.Index].Hex(), false)
if err != nil { if err != nil {
return err return err
} }
@ -832,12 +832,12 @@ func toFilterOptions(options *FilterOptions) core.FilterOptions {
// Convert optional address slice/string to byte slice // Convert optional address slice/string to byte slice
if str, ok := options.Address.(string); ok { if str, ok := options.Address.(string); ok {
opts.Address = [][]byte{common.FromHex(str)} opts.Address = []common.Address{common.HexToAddress(str)}
} else if slice, ok := options.Address.([]interface{}); ok { } else if slice, ok := options.Address.([]interface{}); ok {
bslice := make([][]byte, len(slice)) bslice := make([]common.Address, len(slice))
for i, addr := range slice { for i, addr := range slice {
if saddr, ok := addr.(string); ok { if saddr, ok := addr.(string); ok {
bslice[i] = common.FromHex(saddr) bslice[i] = common.HexToAddress(saddr)
} }
} }
opts.Address = bslice opts.Address = bslice
@ -846,16 +846,15 @@ func toFilterOptions(options *FilterOptions) core.FilterOptions {
opts.Earliest = options.Earliest opts.Earliest = options.Earliest
opts.Latest = options.Latest opts.Latest = options.Latest
topics := make([][][]byte, len(options.Topics)) topics := make([][]common.Hash, len(options.Topics))
for i, topicDat := range options.Topics { for i, topicDat := range options.Topics {
if slice, ok := topicDat.([]interface{}); ok { if slice, ok := topicDat.([]interface{}); ok {
topics[i] = make([][]byte, len(slice)) topics[i] = make([]common.Hash, len(slice))
for j, topic := range slice { for j, topic := range slice {
topics[i][j] = common.FromHex(topic.(string)) topics[i][j] = common.HexToHash(topic.(string))
} }
} else if str, ok := topicDat.(string); ok { } else if str, ok := topicDat.(string); ok {
topics[i] = make([][]byte, 1) topics[i] = []common.Hash{common.HexToHash(str)}
topics[i][0] = common.FromHex(str)
} }
} }
opts.Topics = topics opts.Topics = topics

@ -5,6 +5,7 @@ import (
// "fmt" // "fmt"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
) )
@ -12,14 +13,14 @@ type BlockRes struct {
fullTx bool fullTx bool
BlockNumber int64 `json:"number"` BlockNumber int64 `json:"number"`
BlockHash []byte `json:"hash"` BlockHash common.Hash `json:"hash"`
ParentHash []byte `json:"parentHash"` ParentHash common.Hash `json:"parentHash"`
Nonce []byte `json:"nonce"` Nonce [8]byte `json:"nonce"`
Sha3Uncles []byte `json:"sha3Uncles"` Sha3Uncles common.Hash `json:"sha3Uncles"`
LogsBloom []byte `json:"logsBloom"` LogsBloom types.Bloom `json:"logsBloom"`
TransactionRoot []byte `json:"transactionRoot"` TransactionRoot common.Hash `json:"transactionRoot"`
StateRoot []byte `json:"stateRoot"` StateRoot common.Hash `json:"stateRoot"`
Miner []byte `json:"miner"` Miner common.Address `json:"miner"`
Difficulty int64 `json:"difficulty"` Difficulty int64 `json:"difficulty"`
TotalDifficulty int64 `json:"totalDifficulty"` TotalDifficulty int64 `json:"totalDifficulty"`
Size int64 `json:"size"` Size int64 `json:"size"`
@ -29,7 +30,7 @@ type BlockRes struct {
GasUsed int64 `json:"gasUsed"` GasUsed int64 `json:"gasUsed"`
UnixTimestamp int64 `json:"timestamp"` UnixTimestamp int64 `json:"timestamp"`
Transactions []*TransactionRes `json:"transactions"` Transactions []*TransactionRes `json:"transactions"`
Uncles [][]byte `json:"uncles"` Uncles []common.Hash `json:"uncles"`
} }
func (b *BlockRes) MarshalJSON() ([]byte, error) { func (b *BlockRes) MarshalJSON() ([]byte, error) {
@ -57,14 +58,14 @@ func (b *BlockRes) MarshalJSON() ([]byte, error) {
// convert strict types to hexified strings // convert strict types to hexified strings
ext.BlockNumber = toHex(big.NewInt(b.BlockNumber).Bytes()) ext.BlockNumber = toHex(big.NewInt(b.BlockNumber).Bytes())
ext.BlockHash = toHex(b.BlockHash) ext.BlockHash = b.BlockHash.Hex()
ext.ParentHash = toHex(b.ParentHash) ext.ParentHash = b.ParentHash.Hex()
ext.Nonce = toHex(b.Nonce) ext.Nonce = toHex(b.Nonce[:])
ext.Sha3Uncles = toHex(b.Sha3Uncles) ext.Sha3Uncles = b.Sha3Uncles.Hex()
ext.LogsBloom = toHex(b.LogsBloom) ext.LogsBloom = toHex(b.LogsBloom[:])
ext.TransactionRoot = toHex(b.TransactionRoot) ext.TransactionRoot = b.TransactionRoot.Hex()
ext.StateRoot = toHex(b.StateRoot) ext.StateRoot = b.StateRoot.Hex()
ext.Miner = toHex(b.Miner) ext.Miner = b.Miner.Hex()
ext.Difficulty = toHex(big.NewInt(b.Difficulty).Bytes()) ext.Difficulty = toHex(big.NewInt(b.Difficulty).Bytes())
ext.TotalDifficulty = toHex(big.NewInt(b.TotalDifficulty).Bytes()) ext.TotalDifficulty = toHex(big.NewInt(b.TotalDifficulty).Bytes())
ext.Size = toHex(big.NewInt(b.Size).Bytes()) ext.Size = toHex(big.NewInt(b.Size).Bytes())
@ -80,12 +81,12 @@ func (b *BlockRes) MarshalJSON() ([]byte, error) {
} }
} else { } else {
for i, tx := range b.Transactions { for i, tx := range b.Transactions {
ext.Transactions[i] = toHex(tx.Hash) ext.Transactions[i] = tx.Hash.Hex()
} }
} }
ext.Uncles = make([]string, len(b.Uncles)) ext.Uncles = make([]string, len(b.Uncles))
for i, v := range b.Uncles { for i, v := range b.Uncles {
ext.Uncles[i] = toHex(v) ext.Uncles[i] = v.Hex()
} }
return json.Marshal(ext) return json.Marshal(ext)
@ -124,7 +125,7 @@ func NewBlockRes(block *types.Block) *BlockRes {
v.TxIndex = int64(i) v.TxIndex = int64(i)
res.Transactions[i] = v res.Transactions[i] = v
} }
res.Uncles = make([][]byte, len(block.Uncles())) res.Uncles = make([]common.Hash, len(block.Uncles()))
for i, uncle := range block.Uncles() { for i, uncle := range block.Uncles() {
res.Uncles[i] = uncle.Hash() res.Uncles[i] = uncle.Hash()
} }
@ -132,17 +133,17 @@ func NewBlockRes(block *types.Block) *BlockRes {
} }
type TransactionRes struct { type TransactionRes struct {
Hash []byte `json:"hash"` Hash common.Hash `json:"hash"`
Nonce int64 `json:"nonce"` Nonce int64 `json:"nonce"`
BlockHash []byte `json:"blockHash,omitempty"` BlockHash common.Hash `json:"blockHash,omitempty"`
BlockNumber int64 `json:"blockNumber,omitempty"` BlockNumber int64 `json:"blockNumber,omitempty"`
TxIndex int64 `json:"transactionIndex,omitempty"` TxIndex int64 `json:"transactionIndex,omitempty"`
From []byte `json:"from"` From common.Address `json:"from"`
To []byte `json:"to"` To *common.Address `json:"to"`
Value int64 `json:"value"` Value int64 `json:"value"`
Gas int64 `json:"gas"` Gas int64 `json:"gas"`
GasPrice int64 `json:"gasPrice"` GasPrice int64 `json:"gasPrice"`
Input []byte `json:"input"` Input []byte `json:"input"`
} }
func (t *TransactionRes) MarshalJSON() ([]byte, error) { func (t *TransactionRes) MarshalJSON() ([]byte, error) {
@ -160,13 +161,17 @@ func (t *TransactionRes) MarshalJSON() ([]byte, error) {
Input string `json:"input"` Input string `json:"input"`
} }
ext.Hash = toHex(t.Hash) ext.Hash = t.Hash.Hex()
ext.Nonce = toHex(big.NewInt(t.Nonce).Bytes()) ext.Nonce = toHex(big.NewInt(t.Nonce).Bytes())
ext.BlockHash = toHex(t.BlockHash) ext.BlockHash = t.BlockHash.Hex()
ext.BlockNumber = toHex(big.NewInt(t.BlockNumber).Bytes()) ext.BlockNumber = toHex(big.NewInt(t.BlockNumber).Bytes())
ext.TxIndex = toHex(big.NewInt(t.TxIndex).Bytes()) ext.TxIndex = toHex(big.NewInt(t.TxIndex).Bytes())
ext.From = toHex(t.From) ext.From = t.From.Hex()
ext.To = toHex(t.To) if t.To == nil {
ext.To = "0x00"
} else {
ext.To = t.To.Hex()
}
ext.Value = toHex(big.NewInt(t.Value).Bytes()) ext.Value = toHex(big.NewInt(t.Value).Bytes())
ext.Gas = toHex(big.NewInt(t.Gas).Bytes()) ext.Gas = toHex(big.NewInt(t.Gas).Bytes())
ext.GasPrice = toHex(big.NewInt(t.GasPrice).Bytes()) ext.GasPrice = toHex(big.NewInt(t.GasPrice).Bytes())
@ -179,7 +184,7 @@ func NewTransactionRes(tx *types.Transaction) *TransactionRes {
var v = new(TransactionRes) var v = new(TransactionRes)
v.Hash = tx.Hash() v.Hash = tx.Hash()
v.Nonce = int64(tx.Nonce()) v.Nonce = int64(tx.Nonce())
v.From = tx.From() v.From, _ = tx.From()
v.To = tx.To() v.To = tx.To()
v.Value = tx.Value().Int64() v.Value = tx.Value().Int64()
v.Gas = tx.Gas().Int64() v.Gas = tx.Gas().Int64()

@ -155,11 +155,11 @@ func toLogs(logs state.Logs) (ls []Log) {
for i, log := range logs { for i, log := range logs {
var l Log var l Log
l.Topic = make([]string, len(log.Topics())) l.Topic = make([]string, len(log.Topics()))
l.Address = toHex(log.Address()) l.Address = log.Address().Hex()
l.Data = toHex(log.Data()) l.Data = toHex(log.Data())
l.Number = log.Number() l.Number = log.Number()
for j, topic := range log.Topics() { for j, topic := range log.Topics() {
l.Topic[j] = toHex(topic) l.Topic[j] = topic.Hex()
} }
ls[i] = l ls[i] = l
} }

@ -142,9 +142,9 @@ func NewTx(tx *types.Transaction) *Transaction {
hash := tx.Hash().Hex() hash := tx.Hash().Hex()
receiver := tx.To().Hex() receiver := tx.To().Hex()
if len(receiver) == 0 { if len(receiver) == 0 {
receiver = toHex(core.AddressFromMessage(tx)) receiver = core.AddressFromMessage(tx).Hex()
} }
sender := toHex(tx.From()) sender, _ := tx.From()
createsContract := core.MessageCreatesContract(tx) createsContract := core.MessageCreatesContract(tx)
var data string var data string
@ -154,7 +154,7 @@ func NewTx(tx *types.Transaction) *Transaction {
data = toHex(tx.Data()) data = toHex(tx.Data())
} }
return &Transaction{ref: tx, Hash: hash, Value: common.CurrencyToString(tx.Value()), Address: receiver, Contract: createsContract, Gas: tx.Gas().String(), GasPrice: tx.GasPrice().String(), Data: data, Sender: sender, CreatesContract: createsContract, RawData: toHex(tx.Data())} return &Transaction{ref: tx, Hash: hash, Value: common.CurrencyToString(tx.Value()), Address: receiver, Contract: createsContract, Gas: tx.Gas().String(), GasPrice: tx.GasPrice().String(), Data: data, Sender: sender.Hex(), CreatesContract: createsContract, RawData: toHex(tx.Data())}
} }
func (self *Transaction) ToString() string { func (self *Transaction) ToString() string {

@ -8,10 +8,10 @@ import (
"math/big" "math/big"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
@ -116,14 +116,14 @@ func (self *XEth) State() *State { return self.state }
func (self *XEth) Whisper() *Whisper { return self.whisper } func (self *XEth) Whisper() *Whisper { return self.whisper }
func (self *XEth) BlockByHash(strHash string) *Block { func (self *XEth) BlockByHash(strHash string) *Block {
hash := common.FromHex(strHash) hash := common.HexToHash(strHash)
block := self.chainManager.GetBlock(hash) block := self.chainManager.GetBlock(hash)
return NewBlock(block) return NewBlock(block)
} }
func (self *XEth) EthBlockByHash(strHash string) *types.Block { func (self *XEth) EthBlockByHash(strHash string) *types.Block {
hash := common.FromHex(strHash) hash := common.HexToHash(strHash)
block := self.chainManager.GetBlock(hash) block := self.chainManager.GetBlock(hash)
return block return block
@ -293,9 +293,9 @@ func (self *XEth) PushTx(encodedTx string) (string, error) {
if tx.To() == nil { if tx.To() == nil {
addr := core.AddressFromMessage(tx) addr := core.AddressFromMessage(tx)
return toHex(addr), nil return addr.Hex(), nil
} }
return toHex(tx.Hash()), nil return tx.Hash().Hex(), nil
} }
var ( var (
@ -306,8 +306,8 @@ var (
func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, error) { func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, error) {
statedb := self.State().State() //self.chainManager.TransState() statedb := self.State().State() //self.chainManager.TransState()
msg := callmsg{ msg := callmsg{
from: statedb.GetOrNewStateObject(common.FromHex(fromStr)), from: statedb.GetOrNewStateObject(common.HexToAddress(fromStr)),
to: common.FromHex(toStr), to: common.HexToAddress(toStr),
gas: common.Big(gasStr), gas: common.Big(gasStr),
gasPrice: common.Big(gasPriceStr), gasPrice: common.Big(gasPriceStr),
value: common.Big(valueStr), value: common.Big(valueStr),
@ -330,8 +330,8 @@ func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr st
func (self *XEth) Transact(fromStr, toStr, valueStr, gasStr, gasPriceStr, codeStr string) (string, error) { func (self *XEth) Transact(fromStr, toStr, valueStr, gasStr, gasPriceStr, codeStr string) (string, error) {
var ( var (
from []byte from = common.HexToAddress(fromStr)
to []byte to = common.HexToAddress(toStr)
value = common.NewValue(valueStr) value = common.NewValue(valueStr)
gas = common.NewValue(gasStr) gas = common.NewValue(gasStr)
price = common.NewValue(gasPriceStr) price = common.NewValue(gasPriceStr)
@ -339,10 +339,8 @@ func (self *XEth) Transact(fromStr, toStr, valueStr, gasStr, gasPriceStr, codeSt
contractCreation bool contractCreation bool
) )
from = common.FromHex(fromStr)
data = common.FromHex(codeStr) data = common.FromHex(codeStr)
to = common.FromHex(toStr) if len(toStr) == 0 {
if len(to) == 0 {
contractCreation = true contractCreation = true
} }
@ -368,21 +366,19 @@ func (self *XEth) Transact(fromStr, toStr, valueStr, gasStr, gasPriceStr, codeSt
if contractCreation { if contractCreation {
addr := core.AddressFromMessage(tx) addr := core.AddressFromMessage(tx)
pipelogger.Infof("Contract addr %x\n", addr) pipelogger.Infof("Contract addr %x\n", addr)
}
if types.IsContractAddr(to) { return core.AddressFromMessage(tx).Hex(), nil
return toHex(core.AddressFromMessage(tx)), nil
} }
return toHex(tx.Hash()), nil return tx.Hash().Hex(), nil
} }
func (self *XEth) sign(tx *types.Transaction, from []byte, didUnlock bool) error { func (self *XEth) sign(tx *types.Transaction, from common.Address, didUnlock bool) error {
sig, err := self.accountManager.Sign(accounts.Account{Address: from}, tx.Hash()) sig, err := self.accountManager.Sign(accounts.Account{Address: from.Bytes()}, tx.Hash().Bytes())
if err == accounts.ErrLocked { if err == accounts.ErrLocked {
if didUnlock { if didUnlock {
return fmt.Errorf("sender account still locked after successful unlock") return fmt.Errorf("sender account still locked after successful unlock")
} }
if !self.frontend.UnlockAccount(from) { if !self.frontend.UnlockAccount(from.Bytes()) {
return fmt.Errorf("could not unlock sender account") return fmt.Errorf("could not unlock sender account")
} }
// retry signing, the account should now be unlocked. // retry signing, the account should now be unlocked.
@ -397,17 +393,17 @@ func (self *XEth) sign(tx *types.Transaction, from []byte, didUnlock bool) error
// callmsg is the message type used for call transations. // callmsg is the message type used for call transations.
type callmsg struct { type callmsg struct {
from *state.StateObject from *state.StateObject
to []byte to common.Address
gas, gasPrice *big.Int gas, gasPrice *big.Int
value *big.Int value *big.Int
data []byte data []byte
} }
// accessor boilerplate to implement core.Message // accessor boilerplate to implement core.Message
func (m callmsg) From() []byte { return m.from.Address() } func (m callmsg) From() (common.Address, error) { return m.from.Address(), nil }
func (m callmsg) Nonce() uint64 { return m.from.Nonce() } func (m callmsg) Nonce() uint64 { return m.from.Nonce() }
func (m callmsg) To() []byte { return m.to } func (m callmsg) To() *common.Address { return &m.to }
func (m callmsg) GasPrice() *big.Int { return m.gasPrice } func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
func (m callmsg) Gas() *big.Int { return m.gas } func (m callmsg) Gas() *big.Int { return m.gas }
func (m callmsg) Value() *big.Int { return m.value } func (m callmsg) Value() *big.Int { return m.value }
func (m callmsg) Data() []byte { return m.data } func (m callmsg) Data() []byte { return m.data }

Loading…
Cancel
Save