Merge branch 'master' into 15493

This commit is contained in:
Armani Ferrante 2017-11-16 14:53:32 -08:00 committed by GitHub
commit 3530d5ef40
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 50 additions and 81 deletions

View file

@ -45,7 +45,6 @@ type LogConfig struct {
DisableMemory bool // disable memory capture DisableMemory bool // disable memory capture
DisableStack bool // disable stack capture DisableStack bool // disable stack capture
DisableStorage bool // disable storage capture DisableStorage bool // disable storage capture
FullStorage bool // show full storage (slow)
Limit int // maximum length of output, but zero means unlimited Limit int // maximum length of output, but zero means unlimited
} }
@ -136,14 +135,13 @@ func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost ui
) )
l.changedValues[contract.Address()][address] = value l.changedValues[contract.Address()][address] = value
} }
// copy a snapstot of the current memory state to a new buffer // Copy a snapstot of the current memory state to a new buffer
var mem []byte var mem []byte
if !l.cfg.DisableMemory { if !l.cfg.DisableMemory {
mem = make([]byte, len(memory.Data())) mem = make([]byte, len(memory.Data()))
copy(mem, memory.Data()) copy(mem, memory.Data())
} }
// Copy a snapshot of the current stack state to a new buffer
// copy a snapshot of the current stack state to a new buffer
var stck []*big.Int var stck []*big.Int
if !l.cfg.DisableStack { if !l.cfg.DisableStack {
stck = make([]*big.Int, len(stack.Data())) stck = make([]*big.Int, len(stack.Data()))
@ -151,27 +149,11 @@ func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost ui
stck[i] = new(big.Int).Set(item) stck[i] = new(big.Int).Set(item)
} }
} }
// Copy a snapshot of the current storage to a new container
// Copy the storage based on the settings specified in the log config. If full storage
// is disabled (default) we can use the simple Storage.Copy method, otherwise we use
// the state object to query for all values (slow process).
var storage Storage var storage Storage
if !l.cfg.DisableStorage { if !l.cfg.DisableStorage {
if l.cfg.FullStorage {
storage = make(Storage)
// Get the contract account and loop over each storage entry. This may involve looping over
// the trie and is a very expensive process.
env.StateDB.ForEachStorage(contract.Address(), func(key, value common.Hash) bool {
storage[key] = value
// Return true, indicating we'd like to continue.
return true
})
} else {
// copy a snapshot of the current storage to a new container.
storage = l.changedValues[contract.Address()].Copy() storage = l.changedValues[contract.Address()].Copy()
} }
}
// create a new snaptshot of the EVM. // create a new snaptshot of the EVM.
log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, storage, depth, err} log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, storage, depth, err}

View file

@ -63,32 +63,8 @@ func TestStoreCapture(t *testing.T) {
if len(logger.changedValues[contract.Address()]) == 0 { if len(logger.changedValues[contract.Address()]) == 0 {
t.Fatalf("expected exactly 1 changed value on address %x, got %d", contract.Address(), len(logger.changedValues[contract.Address()])) t.Fatalf("expected exactly 1 changed value on address %x, got %d", contract.Address(), len(logger.changedValues[contract.Address()]))
} }
exp := common.BigToHash(big.NewInt(1)) exp := common.BigToHash(big.NewInt(1))
if logger.changedValues[contract.Address()][index] != exp { if logger.changedValues[contract.Address()][index] != exp {
t.Errorf("expected %x, got %x", exp, logger.changedValues[contract.Address()][index]) t.Errorf("expected %x, got %x", exp, logger.changedValues[contract.Address()][index])
} }
} }
func TestStorageCapture(t *testing.T) {
t.Skip("implementing this function is difficult. it requires all sort of interfaces to be implemented which isn't trivial. The value (the actual test) isn't worth it")
var (
ref = &dummyContractRef{}
contract = NewContract(ref, ref, new(big.Int), 0)
env = NewEVM(Context{}, dummyStateDB{ref: ref}, params.TestChainConfig, Config{EnableJit: false, ForceJit: false})
logger = NewStructLogger(nil)
mem = NewMemory()
stack = newstack()
)
logger.CaptureState(env, 0, STOP, 0, 0, mem, stack, contract, 0, nil)
if ref.calledForEach {
t.Error("didn't expect for each to be called")
}
logger = NewStructLogger(&LogConfig{FullStorage: true})
logger.CaptureState(env, 0, STOP, 0, 0, mem, stack, contract, 0, nil)
if !ref.calledForEach {
t.Error("expected for each to be called")
}
}

View file

@ -333,7 +333,7 @@ func (d *Downloader) Synchronise(id string, head common.Hash, td *big.Int, mode
} }
// synchronise will select the peer and use it for synchronising. If an empty string is given // synchronise will select the peer and use it for synchronising. If an empty string is given
// it will use the best peer possible and synchronize if it's TD is higher than our own. If any of the // it will use the best peer possible and synchronize if its TD is higher than our own. If any of the
// checks fail an error will be returned. This method is synchronous // checks fail an error will be returned. This method is synchronous
func (d *Downloader) synchronise(id string, hash common.Hash, td *big.Int, mode SyncMode) error { func (d *Downloader) synchronise(id string, hash common.Hash, td *big.Int, mode SyncMode) error {
// Mock out the synchronisation if testing // Mock out the synchronisation if testing
@ -1003,8 +1003,8 @@ func (d *Downloader) fetchParts(errCancel error, deliveryCh chan dataPack, deliv
return errCancel return errCancel
case packet := <-deliveryCh: case packet := <-deliveryCh:
// If the peer was previously banned and failed to deliver it's pack // If the peer was previously banned and failed to deliver its pack
// in a reasonable time frame, ignore it's message. // in a reasonable time frame, ignore its message.
if peer := d.peers.Peer(packet.PeerId()); peer != nil { if peer := d.peers.Peer(packet.PeerId()); peer != nil {
// Deliver the received chunk of data and check chain validity // Deliver the received chunk of data and check chain validity
accepted, err := deliver(packet) accepted, err := deliver(packet)
@ -1205,8 +1205,8 @@ func (d *Downloader) processHeaders(origin uint64, td *big.Int) error {
case <-d.cancelCh: case <-d.cancelCh:
} }
} }
// If no headers were retrieved at all, the peer violated it's TD promise that it had a // If no headers were retrieved at all, the peer violated its TD promise that it had a
// better chain compared to ours. The only exception is if it's promised blocks were // better chain compared to ours. The only exception is if its promised blocks were
// already imported by other means (e.g. fecher): // already imported by other means (e.g. fecher):
// //
// R <remote peer>, L <local node>: Both at block 10 // R <remote peer>, L <local node>: Both at block 10

View file

@ -715,40 +715,47 @@ type StructLogRes struct {
Gas uint64 `json:"gas"` Gas uint64 `json:"gas"`
GasCost uint64 `json:"gasCost"` GasCost uint64 `json:"gasCost"`
Depth int `json:"depth"` Depth int `json:"depth"`
Error error `json:"error"` Error error `json:"error,omitempty"`
Stack []string `json:"stack"` Stack *[]string `json:"stack,omitempty"`
Memory []string `json:"memory"` Memory *[]string `json:"memory,omitempty"`
Storage map[string]string `json:"storage"` Storage *map[string]string `json:"storage,omitempty"`
} }
// formatLogs formats EVM returned structured logs for json output // formatLogs formats EVM returned structured logs for json output
func FormatLogs(structLogs []vm.StructLog) []StructLogRes { func FormatLogs(logs []vm.StructLog) []StructLogRes {
formattedStructLogs := make([]StructLogRes, len(structLogs)) formatted := make([]StructLogRes, len(logs))
for index, trace := range structLogs { for index, trace := range logs {
formattedStructLogs[index] = StructLogRes{ formatted[index] = StructLogRes{
Pc: trace.Pc, Pc: trace.Pc,
Op: trace.Op.String(), Op: trace.Op.String(),
Gas: trace.Gas, Gas: trace.Gas,
GasCost: trace.GasCost, GasCost: trace.GasCost,
Depth: trace.Depth, Depth: trace.Depth,
Error: trace.Err, Error: trace.Err,
Stack: make([]string, len(trace.Stack)),
Storage: make(map[string]string),
} }
if trace.Stack != nil {
stack := make([]string, len(trace.Stack))
for i, stackValue := range trace.Stack { for i, stackValue := range trace.Stack {
formattedStructLogs[index].Stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32)) stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
} }
formatted[index].Stack = &stack
}
if trace.Memory != nil {
memory := make([]string, 0, (len(trace.Memory)+31)/32)
for i := 0; i+32 <= len(trace.Memory); i += 32 { for i := 0; i+32 <= len(trace.Memory); i += 32 {
formattedStructLogs[index].Memory = append(formattedStructLogs[index].Memory, fmt.Sprintf("%x", trace.Memory[i:i+32])) memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
} }
formatted[index].Memory = &memory
}
if trace.Storage != nil {
storage := make(map[string]string)
for i, storageValue := range trace.Storage { for i, storageValue := range trace.Storage {
formattedStructLogs[index].Storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue) storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
}
formatted[index].Storage = &storage
} }
} }
return formattedStructLogs return formatted
} }
// rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are // rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are

View file

@ -147,18 +147,22 @@ func NewHTTPServer(cors []string, srv *Server) *http.Server {
// ServeHTTP serves JSON-RPC requests over HTTP. // ServeHTTP serves JSON-RPC requests over HTTP.
func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Permit dumb empty requests for remote health-checks (AWS)
if r.Method == "GET" && r.ContentLength == 0 && r.URL.RawQuery == "" {
return
}
if responseCode, errorMessage := httpErrorResponse(r); responseCode != 0 { if responseCode, errorMessage := httpErrorResponse(r); responseCode != 0 {
http.Error(w, errorMessage, responseCode) http.Error(w, errorMessage, responseCode)
return return
} }
w.Header().Set("content-type", contentType) // All checks passed, create a codec that reads direct from the request body
// untilEOF and writes the response to w and order the server to process a
// create a codec that reads direct from the request body until // single request.
// EOF and writes the response to w and order the server to process
// a single request.
codec := NewJSONCodec(&httpReadWriteNopCloser{r.Body, w}) codec := NewJSONCodec(&httpReadWriteNopCloser{r.Body, w})
defer codec.Close() defer codec.Close()
w.Header().Set("content-type", "application/json")
srv.ServeSingleRequest(codec, OptionMethodInvocation) srv.ServeSingleRequest(codec, OptionMethodInvocation)
} }