This repository was archived by the owner on Oct 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_backend.go
More file actions
346 lines (278 loc) · 8.02 KB
/
test_backend.go
File metadata and controls
346 lines (278 loc) · 8.02 KB
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
337
338
339
340
341
342
343
344
345
346
package ethertest
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/big"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/olekukonko/tablewriter"
"github.com/tokencard/ethertest/backends"
"github.com/tokencard/ethertest/stats"
)
// TestRig ...
type TestRig struct {
genesisAlloc core.GenesisAlloc
contracts map[string]*contract
coverage map[string]*sourceCodeCoverage
tracer *tracer
}
// NewTestRig creates a new instance of a test rig
func NewTestRig() *TestRig {
return &TestRig{
genesisAlloc: core.GenesisAlloc{},
contracts: map[string]*contract{},
coverage: map[string]*sourceCodeCoverage{},
tracer: newTracer(),
}
}
// TestBackend is interface to an go-ethereum test backend
type TestBackend interface {
bind.ContractBackend
BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error)
TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
Commit()
Rollback()
AdjustTime(adjustment time.Duration) error
Close() error
Blockchain() *core.BlockChain
}
type interceptingBackend struct {
TestBackend
sentTransactions []*types.Transaction
tr *TestRig
}
func (ib *interceptingBackend) Commit() {
ib.TestBackend.Commit()
for _, t := range ib.sentTransactions {
r, err := ib.TransactionReceipt(context.Background(), t.Hash())
if err != nil {
panic(err)
}
for _, c := range ib.tr.contracts {
to := t.To()
if to != nil {
c.transactionCommited(*to, t.Data(), r.GasUsed)
}
}
}
ib.sentTransactions = nil
}
func (ib *interceptingBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
err := ib.TestBackend.SendTransaction(ctx, tx)
if err != nil {
return err
}
ib.sentTransactions = append(ib.sentTransactions, tx)
return nil
}
type backendOption func(*backendOptions)
type backendOptions struct {
blockchainTime time.Time
blockGasLimit uint64
}
// WithBlockchainTime sets the initial time on the blockchain.
// If not set, it will default to 1970-01-01T00:00:00Z
// Warning: every commit() will increase the time by 15 seconds.
// Once the blockchain time takes over the current time,
// simulated backend will not accept new blocks.
func WithBlockchainTime(t time.Time) func(*backendOptions) {
return func(opt *backendOptions) {
opt.blockchainTime = t
}
}
// WithBlockGasLimit sets the block limit.
// If not set, it will default to 7981579.
func WithBlockGasLimit(limit uint64) func(*backendOptions) {
return func(opt *backendOptions) {
opt.blockGasLimit = limit
}
}
// NewTestBackend creates a new instance of TestBackend
func (t *TestRig) NewTestBackend(opts ...backendOption) TestBackend {
backendOptions := &backendOptions{
blockGasLimit: 7981579,
blockchainTime: time.Unix(0, 0),
}
for _, opt := range opts {
opt(backendOptions)
}
sb := backends.NewSimulatedBackend(t.genesisAlloc, backendOptions.blockGasLimit, vm.Config{
Debug: true,
Tracer: t,
}, backendOptions.blockchainTime)
t.tracer.reset()
return &interceptingBackend{
TestBackend: sb,
tr: t,
}
}
// AddGenesisAccountAllocation adds a GenesisAccount allocation to the test rig.
// When a new TestBackend is created, current genesis account allocations are used.
func (t *TestRig) AddGenesisAccountAllocation(a common.Address, balance *big.Int) *TestRig {
t.genesisAlloc[a] = core.GenesisAccount{Balance: balance}
return t
}
func (t *TestRig) AddCoverageForContracts(combinedJSON string, contractsPath string) *TestRig {
f, err := os.Open(combinedJSON)
if err != nil {
panic(err)
}
defer f.Close()
sc := &solcCombined{}
err = json.NewDecoder(f).Decode(sc)
if err != nil {
panic(err)
}
sourceCode := map[string][]byte{}
coverages := []*sourceCodeCoverage{}
for _, contractFile := range sc.SourceList {
_, found := sc.Sources[contractFile]
if !found {
available := []string{}
for cf := range sc.Sources {
available = append(available, cf)
}
sort.Strings(available)
panic(fmt.Errorf("Could not find contract %q, available: %#v", contractFile, available))
}
path := filepath.Join(contractsPath, contractFile)
source, err := ioutil.ReadFile(path)
if err != nil {
panic(fmt.Errorf("Could not read %q: %s", path, err.Error()))
}
sourceCode[contractFile] = source
scc := newSourceCodeCoverage(contractFile, source, sc.Sources[contractFile])
t.coverage[contractFile] = scc
coverages = append(coverages, scc)
}
for name := range sourceCode {
_, found := sc.Sources[name]
if !found {
panic(fmt.Errorf("Could not find %q in the combined-json", name))
}
}
for n, s := range sourceCode {
sourceIndex := sc.findSourceIndex(n)
if sourceIndex < 0 {
panic(fmt.Errorf("Could not find %q in the source-index", n))
}
ss := sc.Sources[n]
for cn, scon := range sc.Contracts {
if scon.BinRuntime != "" && strings.HasPrefix(cn+":", n) {
con, err := newContract(cn, t.tracer, s, ss, scon, coverages)
if err != nil {
panic(err)
}
t.contracts[cn] = con
}
}
}
return t
}
func (t *TestRig) PrintGasUsage(w io.Writer) {
if shouldBeSilent() {
return
}
for _, c := range t.contracts {
if !c.hasAnyGasInformation() {
continue
}
tw := tablewriter.NewWriter(w)
fmt.Fprintf(w, "Gas Usage for %q\n", c.name)
tw.SetHeader([]string{"Function Name", "Min", "Med", "Max"})
functions := []*Function{}
for _, f := range c.functions {
functions = append(functions, f)
}
sort.Slice(functions, func(i int, j int) bool {
return functions[i].name < functions[j].name
})
for _, f := range functions {
tw.Append([]string{
f.name,
fmt.Sprintf("%d", stats.Uint64Min(f.gasUsed)),
fmt.Sprintf("%d", stats.Uint64Median(f.gasUsed)),
fmt.Sprintf("%d", stats.Uint64Max(f.gasUsed)),
},
)
}
tw.Render()
fmt.Fprintln(w)
}
}
func (t *TestRig) CoverageOf(name string) float64 {
c, found := t.coverage[name]
if !found {
keys := []string{}
for k := range t.coverage {
keys = append(keys, k)
}
panic(fmt.Errorf("Could not find contract %q, available: %q", name, keys))
}
return c.percentageCovered()
}
func (t *TestRig) ExpectMinimumCoverage(name string, expectedCoverage float64) {
if shouldBeSilent() {
return
}
c, found := t.coverage[name]
if !found {
keys := []string{}
for k := range t.coverage {
keys = append(keys, k)
}
panic(fmt.Errorf("Could not find contract %q, available: %q", name, keys))
}
if c.percentageCovered() < expectedCoverage {
fmt.Println()
fmt.Printf("Coverage for %q:\n", name)
c.Print()
panic(fmt.Errorf("Contract %q has %.2f%% coverage (expected: %.2f%%)", name, c.percentageCovered(), expectedCoverage))
}
fmt.Printf("\nCoverage for %q: %.2f%%\n", name, c.percentageCovered())
}
func (t *TestRig) SaveTrace(w io.Writer) error {
return json.NewEncoder(w).Encode(t.tracer.trace)
}
func (t *TestRig) LastExecuted() string {
return t.tracer.trace.LastStep()
}
func (t *TestRig) CaptureStart(from common.Address, to common.Address, call bool, input []byte, gas uint64, value *big.Int) error {
return nil
}
func (t *TestRig) CaptureState(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, depth int, err error) error {
for _, c := range t.contracts {
c.executed(pc, contract.Address(), contract)
}
return nil
}
func (t *TestRig) CaptureFault(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, depth int, err error) error {
return nil
}
func (t *TestRig) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) error {
return nil
}
func shouldBeSilent() bool {
silent := os.Getenv("SILENT")
if strings.ToLower(silent) == "true" {
return true
}
if strings.ToLower(silent) == "yes" {
return true
}
if silent == "1" {
return true
}
return false
}