-
Notifications
You must be signed in to change notification settings - Fork 112
/
verifier.go
486 lines (454 loc) · 12.4 KB
/
verifier.go
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
package verifier
import (
"encoding/json"
"errors"
"fmt"
"time"
"github.com/iost-official/go-iost/core/blockcache"
"github.com/iost-official/go-iost/core/global"
"github.com/iost-official/go-iost/common"
"github.com/iost-official/go-iost/core/block"
"github.com/iost-official/go-iost/core/tx"
"github.com/iost-official/go-iost/core/txpool"
"github.com/iost-official/go-iost/ilog"
"github.com/iost-official/go-iost/vm"
"github.com/iost-official/go-iost/vm/database"
)
// values
var (
ErrExpiredTx = errors.New("expired tx")
ErrNotArrivedTx = errors.New("not arrived tx")
ErrInvalidMode = errors.New("invalid mode")
)
// Verifier ..
type Verifier struct {
}
// Config config of verifier
type Config struct {
Mode int
Timeout time.Duration
TxTimeLimit time.Duration
Thread int
}
// Info info in block
type Info struct {
Mode int `json:"mode"`
Thread int `json:"thread"`
Batch []int `json:"batch"`
}
//var ParallelMask int64 = 1 // 0000 0001
// Exec exec single tx and flush changes to db
func (v *Verifier) Exec(bh *block.BlockHead, db database.IMultiValue, t *tx.Tx, limit time.Duration) (*tx.TxReceipt, error) {
var isolator vm.Isolator
vi := database.NewVisitor(100, db, bh.Rules())
var l ilog.Logger
l.Stop()
err := isolator.Prepare(bh, vi, &l)
if err != nil {
return &tx.TxReceipt{}, err
}
err = isolator.PrepareTx(t, limit)
if err != nil {
return &tx.TxReceipt{}, err
}
r, err := isolator.Run()
if err != nil {
return &tx.TxReceipt{}, err
}
isolator.Commit()
return r, err
}
// Try exec tx and only return receipt
func (v *Verifier) Try(bh *block.BlockHead, db database.IMultiValue, t *tx.Tx, limit time.Duration) (*tx.TxReceipt, error) {
var isolator vm.Isolator
vi := database.NewVisitor(100, db, bh.Rules())
var l ilog.Logger
l.Stop()
err := isolator.Prepare(bh, vi, &l)
if err != nil {
return &tx.TxReceipt{}, err
}
err = isolator.PrepareTx(t, limit)
if err != nil {
return &tx.TxReceipt{}, err
}
r, err := isolator.Run()
if err != nil {
return &tx.TxReceipt{}, err
}
return r, err
}
// Gen gen block
func (v *Verifier) Gen(blk, parent *block.Block, witnessList *blockcache.WitnessList, db database.IMultiValue, iter *txpool.SortedTxMap, c *Config) (droplist []*tx.Tx, errs []error, err error) {
isolator := &vm.Isolator{}
baseTx, err := NewBaseTx(blk, parent, witnessList)
if err != nil {
return nil, nil, err
}
r, err := blockBaseExec(blk, db, isolator, baseTx, c)
if err != nil {
return nil, nil, err
}
blk.Txs = append(blk.Txs, baseTx)
blk.Receipts = append(blk.Receipts, r)
var pi = NewProvider(iter)
switch c.Mode {
case 0:
err = baseGen(blk, db, pi, isolator, c)
droplist, errs = pi.List()
pi.Close()
return
case 1:
batcher := NewBatcher()
err = batchGen(blk, db, pi, batcher, c)
droplist, errs = pi.List()
pi.Close()
return
}
pi.Close()
return []*tx.Tx{}, []error{}, fmt.Errorf("mode unexpected: %v", c.Mode)
}
func blockBaseExec(blk *block.Block, db database.IMultiValue, isolator *vm.Isolator, t *tx.Tx, c *Config) (tr *tx.TxReceipt, err error) {
vi := database.NewVisitor(100, db, blk.Head.Rules())
isolator.Prepare(blk.Head, vi, getLogger(global.GetGlobalConf() != nil && global.GetGlobalConf().Log.EnableContractLog))
isolator.TriggerBlockBaseMode()
err = isolator.PrepareTx(t, c.Timeout)
if err != nil {
return nil, err
}
r, err := isolator.Run()
if err != nil {
return nil, err
}
if r.Status.Code != tx.Success {
return nil, fmt.Errorf(r.Status.Message)
}
isolator.Commit()
isolator.ClearTx()
return r, nil
}
// nolint:gocyclo
func baseGen(blk *block.Block, db database.IMultiValue, provider Provider, isolator *vm.Isolator, c *Config) (err error) {
info := Info{
Mode: 0,
}
var tn time.Time
to := time.Now().Add(c.Timeout)
blockGasLimit := common.MaxBlockGasLimit
L:
for tn.Before(to) {
isolator.ClearTx()
tn = time.Now()
limit := to.Sub(tn)
if limit > c.TxTimeLimit {
limit = c.TxTimeLimit
}
if limit < 500*time.Microsecond {
break L
}
t := provider.Tx()
if t == nil {
break L
}
if !t.IsCreatedBefore(blk.Head.Time) {
ilog.Debugf(
"Tx %v has not arrived. tx time is %v, blk time is %v",
common.Base58Encode(t.Hash()),
t.Time,
blk.Head.Time,
)
continue L
}
if t.Delay > 0 {
ilog.Debug("Ignore delay tx.")
continue L
}
if tx.CheckBadTx(t) != nil {
ilog.Errorf("bad tx %v", t)
continue L
}
if t.IsExpired(blk.Head.Time) && !t.IsDefer() {
ilog.Errorf(
"Tx %v is expired, tx time is %v, tx expiration time is %v, blk time is %v",
common.Base58Encode(t.Hash()),
t.Time,
t.Expiration,
blk.Head.Time,
)
provider.Drop(t, ErrExpiredTx)
continue L
}
if t.GasLimit > blockGasLimit {
continue L
}
err := isolator.PrepareTx(t, limit)
if err != nil {
ilog.Errorf("PrepareTx failed. tx %v limit %v err %v", t.String(), limit, err)
provider.Drop(t, err)
continue L
}
var r *tx.TxReceipt
r, err = isolator.Run()
if err != nil {
ilog.Errorf("isolator run error %v %v", t.String(), err)
provider.Drop(t, err)
continue L
}
if r.Status.Code == tx.ErrorTimeout && limit < c.TxTimeLimit {
ilog.Debugf(
"isolator run time out, but time limit %v less than std time limit %v",
limit,
c.TxTimeLimit,
)
provider.Return(t)
break L
}
//ilog.Debugf("exec tx %v success", common.Base58Encode(t.Hash()))
r, err = isolator.PayCost()
if err != nil {
ilog.Errorf("pay cost err %v %v", t.String(), err)
provider.Drop(t, err)
continue L
}
isolator.Commit()
blk.Txs = append(blk.Txs, t)
blk.Receipts = append(blk.Receipts, r)
blockGasLimit -= r.GasUsage
}
buf, err := json.Marshal(info)
if err != nil {
panic(err)
}
blk.Head.Info = buf
for _, t := range blk.Txs {
provider.Drop(t, nil)
}
return err
}
func batchGen(blk *block.Block, db database.IMultiValue, provider Provider, batcher Batcher, c *Config) (err error) {
info := Info{
Mode: 1,
Thread: c.Thread,
Batch: make([]int, 0),
}
tn := time.Now()
to := time.Now().Add(c.Timeout)
for tn.Before(to) {
limit := to.Sub(tn)
if limit > c.TxTimeLimit {
limit = c.TxTimeLimit
}
batch := batcher.Batch(blk.Head, db, provider, limit, c.Thread)
info.Batch = append(info.Batch, len(batch.Txs))
for i, t := range batch.Txs {
if limit < c.TxTimeLimit && batch.Receipts[i].Status.Code == 5 {
provider.Return(t)
continue
}
blk.Txs = append(blk.Txs, t)
blk.Receipts = append(blk.Receipts, batch.Receipts[i])
provider.Drop(t, nil)
}
}
blk.Head.Info, err = json.Marshal(info)
return err
}
func getLogger(enableContractLog bool) *ilog.Logger {
if !enableContractLog {
var l ilog.Logger
l.Stop()
return &l
}
return ilog.DefaultLogger()
}
// Verify verify block generated by Verifier
func (v *Verifier) Verify(blk, parent *block.Block, witnessList *blockcache.WitnessList, db database.IMultiValue, c *Config) error {
ri := blk.Head.Info
var info Info
err := json.Unmarshal(ri, &info)
if err != nil {
return err
}
err = verifyBlockBase(blk, parent, witnessList, db, c)
if err != nil {
return err
}
switch info.Mode {
case 0:
isolator := vm.Isolator{}
vi, _ := database.NewBatchVisitor(database.NewBatchVisitorRoot(100, db, blk.Head.Rules()))
isolator.Prepare(blk.Head, vi, getLogger(false))
return baseVerify(isolator, c, blk.Txs[1:], blk.Receipts[1:], blk)
/* case 1: */
// bs := batches(blk, info)
// var batcher Batcher
// return batchVerify(batcher, blk.Head, c, db, bs, blk)
/* } */
default:
return ErrInvalidMode
}
}
/*
func batches(blk *block.Block, info Info) []*Batch {
var rtn = make([]*Batch, 0)
var k = 0
for _, j := range info.Batch {
txs := blk.Txs[k:j]
rs := blk.Receipts[k:j]
k = j
rtn = append(rtn, &Batch{
Txs: txs,
Receipts: rs,
})
}
return rtn
}*/
func verifyBlockBase(blk, parent *block.Block, witnessList *blockcache.WitnessList, db database.IMultiValue, c *Config) error {
if len(blk.Txs) < 1 || len(blk.Receipts) < 1 {
return fmt.Errorf("block did not contain block base tx")
}
baseTx, err := NewBaseTx(blk, parent, witnessList)
if err != nil {
return err
}
for i, a := range blk.Txs[0].Actions {
if a.ActionName != baseTx.Actions[i].ActionName ||
a.Contract != baseTx.Actions[i].Contract ||
a.Data != baseTx.Actions[i].Data {
ilog.Warnf("witnessList: %+v", witnessList)
return fmt.Errorf("block base tx not match, verifyBaseTxAction: %+v\n, localBaseTxAction: %+v", a, baseTx.Actions[i])
}
}
isolator := &vm.Isolator{}
r, err := blockBaseExec(blk, db, isolator, blk.Txs[0], c)
if err != nil {
return err
}
if r.Status.Code != tx.Success {
return fmt.Errorf("block base tx receipt error: %v", r.Status.Message)
}
err = checkReceiptEqual(blk.Receipts[0], r)
if err != nil {
return err
}
return nil
}
func verify(isolator vm.Isolator, t *tx.Tx, r *tx.TxReceipt, timeout time.Duration, isBlockBase bool, blk *block.Block) error { // nolint
if !t.IsCreatedBefore(blk.Head.Time) {
return ErrNotArrivedTx
}
if t.IsExpired(blk.Head.Time) && !t.IsDefer() {
return ErrExpiredTx
}
isolator.ClearTx()
if isBlockBase {
isolator.TriggerBlockBaseMode()
}
var to time.Duration
if r.Status.Code == tx.ErrorTimeout {
if blk.Head.Rules().IsFork3_0_10 {
to = 0
} else {
to = timeout / 2
}
} else {
to = timeout * 2
}
err := isolator.PrepareTx(t, to)
if err != nil {
return err
}
_, err = isolator.Run()
if err != nil {
return err
}
receipt, err := isolator.PayCost()
if err != nil {
return err
}
err = checkReceiptEqual(r, receipt)
if err != nil {
return err
}
isolator.Commit()
return nil
}
func checkReceiptEqual(r *tx.TxReceipt, receipt *tx.TxReceipt) error {
if r.Status.Code != receipt.Status.Code {
return fmt.Errorf("receipt not match, status not same: %v != %v \n%v\n%v", r.Status, receipt.Status, r, receipt)
}
if r.Status.Code == tx.Success {
if r.Status.Message != receipt.Status.Message {
return fmt.Errorf("receipt not match, status not same: %v != %v \n%v\n%v", r.Status, receipt.Status, r, receipt)
}
}
if r.GasUsage != receipt.GasUsage {
return fmt.Errorf("receipt not match, gas usage not same: %v != %v \n%v\n%v", r.GasUsage, receipt.GasUsage, r, receipt)
}
if len(r.RAMUsage) != len(receipt.RAMUsage) {
return fmt.Errorf("receipt not match, ram usage length not same: %v != %v \n%v\n%v", len(r.RAMUsage), len(receipt.RAMUsage), r, receipt)
}
for k, v := range r.RAMUsage {
if v != receipt.RAMUsage[k] {
return fmt.Errorf("receipt not match, ram usage not same: %v != %v \n%v\n%v", v, receipt.RAMUsage[k], r, receipt)
}
}
if len(r.Receipts) != len(receipt.Receipts) {
return fmt.Errorf("receipt not match, receipts length not same: %v != %v \n%v\n%v", len(r.Receipts), len(receipt.Receipts), r, receipt)
}
for i, br := range r.Receipts {
if br.FuncName != receipt.Receipts[i].FuncName {
return fmt.Errorf("receipt not match, funcname not same: %v != %v \n%v\n%v", br.FuncName, receipt.Receipts[i].FuncName, r, receipt)
}
if br.Content != receipt.Receipts[i].Content {
return fmt.Errorf("receipt not match, content not same: %v != %v \n%v\n%v", br.Content, receipt.Receipts[i].Content, r, receipt)
}
}
if len(r.Returns) != len(receipt.Returns) {
return fmt.Errorf("receipt not match, returns length not same: %v != %v \n%v\n%v", len(r.Returns), len(receipt.Returns), r, receipt)
}
for i, br := range r.Returns {
if br != receipt.Returns[i] {
return fmt.Errorf("receipt not match, returns not same: %v != %v \n%v\n%v", br, receipt.Returns[i], r, receipt)
}
}
return nil
}
func baseVerify(engine vm.Isolator, c *Config, txs []*tx.Tx, receipts []*tx.TxReceipt, blk *block.Block) error {
blockGasLimit := common.MaxBlockGasLimit
blockGas := int64(0)
for _, r := range receipts {
blockGas += r.GasUsage
}
if blockGas > blockGasLimit {
return fmt.Errorf(
"Block %v include gas %v, exceeds maximum limit %v",
common.Base58Encode(blk.HeadHash()),
blockGas/100,
blockGasLimit/100,
)
}
for k, t := range txs {
err := verify(engine, t, receipts[k], c.TxTimeLimit, false, blk)
if err != nil {
return err
}
}
return nil
}
/*
func batchVerify(verifier Batcher, bh *block.BlockHead, c *Config, db database.IMultiValue, batches []*Batch, blk *block.Block) error {
for _, batch := range batches {
err := verifier.Verify(bh, db, func(e vm.Isolator, t *tx.Tx, r *tx.TxReceipt) error {
err := verify(e, t, r, c.TxTimeLimit, false, blk)
if err != nil {
return err
}
return nil
}, batch)
if err != nil {
return err
}
}
return nil
}*/