aboutsummaryrefslogtreecommitdiffstats
path: root/eth/tracers/tracers_test.go
blob: 3ee12dd7f0007f0fd7f700349fe8f485c28e8411 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package tracers

import (
    "crypto/ecdsa"
    "crypto/rand"
    "encoding/json"
    "io/ioutil"
    "math/big"
    "path/filepath"
    "reflect"
    "strings"
    "testing"

    "github.com/dexon-foundation/dexon/common"
    "github.com/dexon-foundation/dexon/common/hexutil"
    "github.com/dexon-foundation/dexon/common/math"
    "github.com/dexon-foundation/dexon/core"
    "github.com/dexon-foundation/dexon/core/types"
    "github.com/dexon-foundation/dexon/core/vm"
    "github.com/dexon-foundation/dexon/core/vm/evm"
    "github.com/dexon-foundation/dexon/core/vm/tools"
    "github.com/dexon-foundation/dexon/crypto"
    "github.com/dexon-foundation/dexon/ethdb"
    "github.com/dexon-foundation/dexon/params"
    "github.com/dexon-foundation/dexon/rlp"
    "github.com/dexon-foundation/dexon/tests"
)

// To generate a new callTracer test, copy paste the makeTest method below into
// a Geth console and call it with a transaction hash you which to export.

/*
// makeTest generates a callTracer test by running a prestate reassembled and a
// call trace run, assembling all the gathered information into a test case.
var makeTest = function(tx, rewind) {
  // Generate the genesis block from the block, transaction and prestate data
  var block   = eth.getBlock(eth.getTransaction(tx).blockHash);
  var genesis = eth.getBlock(block.parentHash);

  delete genesis.gasUsed;
  delete genesis.logsBloom;
  delete genesis.parentHash;
  delete genesis.receiptsRoot;
  delete genesis.sha3Uncles;
  delete genesis.size;
  delete genesis.transactions;
  delete genesis.transactionsRoot;
  delete genesis.uncles;

  genesis.gasLimit  = genesis.gasLimit.toString();
  genesis.number    = genesis.number.toString();
  genesis.timestamp = genesis.timestamp.toString();

  genesis.alloc = debug.traceTransaction(tx, {tracer: "prestateTracer", rewind: rewind});
  for (var key in genesis.alloc) {
    genesis.alloc[key].nonce = genesis.alloc[key].nonce.toString();
  }
  genesis.config = admin.nodeInfo.protocols.eth.config;

  // Generate the call trace and produce the test input
  var result = debug.traceTransaction(tx, {tracer: "callTracer", rewind: rewind});
  delete result.time;

  console.log(JSON.stringify({
    genesis: genesis,
    context: {
      number:     block.number.toString(),
      difficulty: block.difficulty,
      timestamp:  block.timestamp.toString(),
      gasLimit:   block.gasLimit.toString(),
      miner:      block.miner,
    },
    input:  eth.getRawTransaction(tx),
    result: result,
  }, null, 2));
}
*/
const (
    gasDiffUnit   = 204
    createGasDiff = 200
)

// callTrace is the result of a callTracer run.
type callTrace struct {
    Type    string          `json:"type"`
    From    common.Address  `json:"from"`
    To      common.Address  `json:"to"`
    Input   hexutil.Bytes   `json:"input"`
    Output  hexutil.Bytes   `json:"output"`
    Gas     *hexutil.Uint64 `json:"gas,omitempty"`
    GasUsed *hexutil.Uint64 `json:"gasUsed,omitempty"`
    Value   *hexutil.Big    `json:"value,omitempty"`
    Error   string          `json:"error,omitempty"`
    Calls   []callTrace     `json:"calls,omitempty"`
}

type callContext struct {
    Number     math.HexOrDecimal64   `json:"number"`
    Difficulty *math.HexOrDecimal256 `json:"difficulty"`
    Time       math.HexOrDecimal64   `json:"timestamp"`
    GasLimit   math.HexOrDecimal64   `json:"gasLimit"`
    Miner      common.Address        `json:"miner"`
}

// callTracerTest defines a single test to check the call tracer against.
type callTracerTest struct {
    Genesis *core.Genesis `json:"genesis"`
    Context *callContext  `json:"context"`
    Input   string        `json:"input"`
    Result  *callTrace    `json:"result"`
}

func TestPrestateTracerCreate2(t *testing.T) {
    unsigned_tx := types.NewTransaction(1, common.HexToAddress("0x00000000000000000000000000000000deadbeef"),
        new(big.Int), 5000000, big.NewInt(1), []byte{})

    privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), rand.Reader)
    if err != nil {
        t.Fatalf("err %v", err)
    }
    signer := types.NewEIP155Signer(big.NewInt(1))
    tx, err := types.SignTx(unsigned_tx, signer, privateKeyECDSA)
    if err != nil {
        t.Fatalf("err %v", err)
    }
    /**
        This comes from one of the test-vectors on the Skinny Create2 - EIP

        address 0x00000000000000000000000000000000deadbeef
        salt 0x00000000000000000000000000000000000000000000000000000000cafebabe
        init_code 0xdeadbeef
        gas (assuming no mem expansion): 32006
        result: 0x60f3f640a8508fC6a86d45DF051962668E1e8AC7
    */
    origin, _ := signer.Sender(tx)
    context := vm.Context{
        CanTransfer: core.CanTransfer,
        Transfer:    core.Transfer,
        Origin:      origin,
        Coinbase:    common.Address{},
        BlockNumber: new(big.Int).SetUint64(8000000),
        Time:        new(big.Int).SetUint64(5),
        Difficulty:  big.NewInt(0x30000),
        GasLimit:    uint64(6000000),
        GasPrice:    big.NewInt(1),
    }
    alloc := core.GenesisAlloc{}
    // The code pushes 'deadbeef' into memory, then the other params, and calls CREATE2, then returns
    // the address
    alloc[common.HexToAddress("0x00000000000000000000000000000000deadbeef")] = core.GenesisAccount{
        Nonce:   1,
        Code:    hexutil.MustDecode("0x63deadbeef60005263cafebabe6004601c6000F560005260206000F3"),
        Balance: big.NewInt(1),
    }
    alloc[origin] = core.GenesisAccount{
        Nonce:   1,
        Code:    []byte{},
        Balance: big.NewInt(500000000000000),
    }
    statedb := tests.MakePreState(ethdb.NewMemDatabase(), alloc)
    // Create the tracer, the EVM environment and run it
    tracer, err := New("prestateTracer")
    if err != nil {
        t.Fatalf("failed to create call tracer: %v", err)
    }
    vmConfig := [vm.NUMS]interface{}{}
    vmConfig[vm.EVM] = evm.Config{Tracer: tracer, Debug: true}
    pack := vm.NewExecPack(&context, statedb, params.MainnetChainConfig, vmConfig)

    msg, err := tx.AsMessage(signer)
    if err != nil {
        t.Fatalf("failed to prepare transaction for tracing: %v", err)
    }
    st := core.NewStateTransition(&pack, msg, new(core.GasPool).AddGas(tx.Gas()))
    core.TestingMode = true
    if _, _, _, err = st.TransitionDb(); err != nil {
        t.Fatalf("failed to execute transaction: %v", err)
    }
    // Retrieve the trace result and compare against the etalon
    res, err := tracer.GetResult()
    if err != nil {
        t.Fatalf("failed to retrieve trace result: %v", err)
    }
    ret := make(map[string]interface{})
    if err := json.Unmarshal(res, &ret); err != nil {
        t.Fatalf("failed to unmarshal trace result: %v", err)
    }
    if _, has := ret["0x60f3f640a8508fc6a86d45df051962668e1e8ac7"]; !has {
        t.Fatalf("Expected 0x60f3f640a8508fc6a86d45df051962668e1e8ac7 in result")
    }
}

func setTx(toolTx *tools.Transaction, tx *types.Transaction, patchPayload bool) (*types.Transaction, int, error) {
    rTx := new(types.Transaction)
    // Patch bytecode and load to tx
    originalLen := len(toolTx.Data.Payload)
    if patchPayload {
        toolTx.Data.Payload = tools.PatchBinary(toolTx.Data.Payload)
    }
    afterLen := len(toolTx.Data.Payload)
    payloadLenDiff := afterLen - originalLen
    toolTx.Data.GasLimit = toolTx.Data.GasLimit + uint64(payloadLenDiff*gasDiffUnit)
    encodeByte, _ := rlp.EncodeToBytes(toolTx)
    if err := rlp.DecodeBytes(encodeByte, rTx); err != nil {
        return nil, 0, err
    }
    rTx.SetFrom(tx)
    return rTx, payloadLenDiff, nil
}

// Iterates over all the input-output datasets in the tracer test harness and
// runs the JavaScript tracers against them.
func TestCallTracer(t *testing.T) {
    files, err := ioutil.ReadDir("testdata")
    if err != nil {
        t.Fatalf("failed to retrieve tracer test suite: %v", err)
    }
    for _, file := range files {
        if !strings.HasPrefix(file.Name(), "call_tracer_") {
            continue
        }
        file := file // capture range variable
        t.Run(camel(strings.TrimSuffix(strings.TrimPrefix(file.Name(), "call_tracer_"), ".json")), func(t *testing.T) {
            t.Parallel()
            // Call tracer test found, read if from disk
            blob, err := ioutil.ReadFile(filepath.Join("testdata", file.Name()))
            if err != nil {
                t.Fatalf("failed to read testcase: %v", err)
            }
            test := new(callTracerTest)
            if err := json.Unmarshal(blob, test); err != nil {
                t.Fatalf("failed to parse testcase: %v", err)
            }
            for k, v := range test.Genesis.Alloc {
                v.Code = tools.PatchBinary(v.Code)
                test.Genesis.Alloc[k] = v
            }
            // Configure a blockchain with the given prestate
            tx := new(types.Transaction)
            toolTx := new(tools.Transaction)
            if err := rlp.DecodeBytes(common.FromHex(test.Input), toolTx); err != nil {
                t.Fatalf("failed to parse testcase input: %v", err)
            }
            if err := rlp.DecodeBytes(common.FromHex(test.Input), tx); err != nil {
                t.Fatalf("failed to parse testcase input: %v", err)
            }
            signer := types.MakeSigner(test.Genesis.Config, new(big.Int).SetUint64(uint64(test.Context.Number)))

            // Get correct sender address
            origin, _ := signer.Sender(tx)
            tx.AsMessage(signer)

            tx, payloadLenDiff, err := setTx(toolTx, tx, test.Result.Type == "CREATE")
            if err != nil {
                t.Fatalf("failed to set tx: %v", err)
            }

            context := vm.Context{
                CanTransfer: core.CanTransfer,
                Transfer:    core.Transfer,
                Origin:      origin,
                Coinbase:    test.Context.Miner,
                BlockNumber: new(big.Int).SetUint64(uint64(test.Context.Number)),
                Time:        new(big.Int).SetUint64(uint64(test.Context.Time)),
                Difficulty:  (*big.Int)(test.Context.Difficulty),
                GasLimit:    uint64(test.Context.GasLimit),
                GasPrice:    tx.GasPrice(),
            }
            statedb := tests.MakePreState(ethdb.NewMemDatabase(), test.Genesis.Alloc)

            // Create the tracer, the EVM environment and run it
            tracer, err := New("callTracer")
            if err != nil {
                t.Fatalf("failed to create call tracer: %v", err)
            }
            vmConfig := [vm.NUMS]interface{}{}
            vmConfig[vm.EVM] = evm.Config{Tracer: tracer, Debug: true}
            pack := vm.NewExecPack(&context, statedb, test.Genesis.Config, vmConfig)
            msg, err := tx.AsMessage(signer)
            if err != nil {
                t.Fatalf("failed to prepare transaction for tracing: %v", err)
            }
            st := core.NewStateTransition(&pack, msg, new(core.GasPool).AddGas(tx.Gas()))
            if _, _, _, err = st.TransitionDb(); err != nil {
                t.Fatalf("failed to execute transaction: %v", err)
            }
            // Retrieve the trace result and compare against the etalon
            res, err := tracer.GetResult()
            if err != nil {
                t.Fatalf("failed to retrieve trace result: %v", err)
            }
            ret := new(callTrace)
            if err := json.Unmarshal(res, ret); err != nil {
                t.Fatalf("failed to unmarshal trace result: %v", err)
            }

            updateResultInput(test.Result, 0)
            *test.Result.Gas += hexutil.Uint64(payloadLenDiff * (gasDiffUnit - 4))
            *test.Result.GasUsed += hexutil.Uint64(payloadLenDiff * (gasDiffUnit - 4))
            if test.Result.Type == "CREATE" {
                *test.Result.GasUsed -= hexutil.Uint64(createGasDiff)
            }
            if !reflect.DeepEqual(ret, test.Result) {
                t.Fatalf("trace mismatch: \nhave %+v\nwant %+v", ret, test.Result)
            }
        })
    }
}
func updateResultInput(result *callTrace, depth int) {
    for i := range result.Calls {
        updateResultInput(&result.Calls[i], depth+1)
    }
    if result.Type == "CREATE" {
        result.Output = tools.PatchBinary(result.Output)
    }
    result.Input = tools.PatchBinary(result.Input)
    if len(result.Input) > 0 && result.Type == "CREATE" && depth == 0 {
        result.Input = result.Input[1:]
    }
}