OSDN Git Service

update for the validation level test
[bytom/bytom.git] / protocol / validation / validation_test.go
1 package validation
2
3 import (
4         "fmt"
5         "math"
6         "testing"
7         "time"
8
9         "github.com/bytom/crypto/sha3pool"
10         "github.com/bytom/errors"
11         "github.com/bytom/protocol/bc"
12         "github.com/bytom/protocol/bc/legacy"
13         "github.com/bytom/protocol/validation"
14         "github.com/bytom/protocol/vm"
15         "github.com/bytom/testutil"
16
17         "github.com/davecgh/go-spew/spew"
18         "github.com/golang/protobuf/proto"
19 )
20
21 func init() {
22         spew.Config.DisableMethods = true
23 }
24
25 func TestTxValidation(t *testing.T) {
26         var (
27                 tx      *bc.Tx
28                 vs      *validationState
29                 fixture *txFixture
30
31                 // the mux from tx, pulled out for convenience
32                 mux *bc.Mux
33         )
34
35         cases := []struct {
36                 desc string // description of the test case
37                 f    func() // function to adjust tx, vs, and/or mux
38                 err  error  // expected error
39         }{
40                 {
41                         desc: "base case",
42                 },
43                 {
44                         desc: "failing mux program",
45                         f: func() {
46                                 mux.Program.Code = []byte{byte(vm.OP_FALSE)}
47                         },
48                         err: vm.ErrFalseVMResult,
49                 },
50                 {
51                         desc: "unbalanced mux amounts",
52                         f: func() {
53                                 mux.Sources[0].Value.Amount++
54                                 iss := tx.Entries[*mux.Sources[0].Ref].(*bc.Issuance)
55                                 iss.WitnessDestination.Value.Amount++
56                         },
57                         err: errUnbalanced,
58                 },
59                 {
60                         desc: "overflowing mux source amounts",
61                         f: func() {
62                                 mux.Sources[0].Value.Amount = math.MaxInt64
63                                 iss := tx.Entries[*mux.Sources[0].Ref].(*bc.Issuance)
64                                 iss.WitnessDestination.Value.Amount = math.MaxInt64
65                         },
66                         err: errOverflow,
67                 },
68                 {
69                         desc: "underflowing mux destination amounts",
70                         f: func() {
71                                 mux.WitnessDestinations[0].Value.Amount = math.MaxInt64
72                                 out := tx.Entries[*mux.WitnessDestinations[0].Ref].(*bc.Output)
73                                 out.Source.Value.Amount = math.MaxInt64
74                                 mux.WitnessDestinations[1].Value.Amount = math.MaxInt64
75                                 out = tx.Entries[*mux.WitnessDestinations[1].Ref].(*bc.Output)
76                                 out.Source.Value.Amount = math.MaxInt64
77                         },
78                         err: errOverflow,
79                 },
80                 {
81                         desc: "unbalanced mux assets",
82                         f: func() {
83                                 mux.Sources[1].Value.AssetId = newAssetID(255)
84                                 sp := tx.Entries[*mux.Sources[1].Ref].(*bc.Spend)
85                                 sp.WitnessDestination.Value.AssetId = newAssetID(255)
86                         },
87                         err: errUnbalanced,
88                 },
89                 {
90                         desc: "nonempty mux exthash",
91                         f: func() {
92                                 mux.ExtHash = newHash(1)
93                         },
94                         err: errNonemptyExtHash,
95                 },
96                 {
97                         desc: "nonempty mux exthash, but that's OK",
98                         f: func() {
99                                 tx.Version = 2
100                                 mux.ExtHash = newHash(1)
101                         },
102                 },
103                 {
104                         desc: "failing nonce program",
105                         f: func() {
106                                 iss := txIssuance(t, tx, 0)
107                                 nonce := tx.Entries[*iss.AnchorId].(*bc.Nonce)
108                                 nonce.Program.Code = []byte{byte(vm.OP_FALSE)}
109                         },
110                         err: vm.ErrFalseVMResult,
111                 },
112                 {
113                         desc: "nonce exthash nonempty",
114                         f: func() {
115                                 iss := txIssuance(t, tx, 0)
116                                 nonce := tx.Entries[*iss.AnchorId].(*bc.Nonce)
117                                 nonce.ExtHash = newHash(1)
118                         },
119                         err: errNonemptyExtHash,
120                 },
121                 {
122                         desc: "nonce exthash nonempty, but that's OK",
123                         f: func() {
124                                 tx.Version = 2
125                                 iss := txIssuance(t, tx, 0)
126                                 nonce := tx.Entries[*iss.AnchorId].(*bc.Nonce)
127                                 nonce.ExtHash = newHash(1)
128                         },
129                 },
130                 {
131                         desc: "mismatched output source / mux dest position",
132                         f: func() {
133                                 tx.Entries[*tx.ResultIds[0]].(*bc.Output).Source.Position = 1
134                         },
135                         err: errMismatchedPosition,
136                 },
137                 {
138                         desc: "mismatched output source and mux dest",
139                         f: func() {
140                                 // For this test, it's necessary to construct a mostly
141                                 // identical second transaction in order to get a similar but
142                                 // not equal output entry for the mux to falsely point
143                                 // to. That entry must be added to the first tx's Entries map.
144                                 fixture.txOutputs[0].ReferenceData = []byte{1}
145                                 fixture2 := sample(t, fixture)
146                                 tx2 := legacy.NewTx(*fixture2.tx).Tx
147                                 out2ID := tx2.ResultIds[0]
148                                 out2 := tx2.Entries[*out2ID].(*bc.Output)
149                                 tx.Entries[*out2ID] = out2
150                                 mux.WitnessDestinations[0].Ref = out2ID
151                         },
152                         err: errMismatchedReference,
153                 },
154                 {
155                         desc: "invalid mux destination position",
156                         f: func() {
157                                 mux.WitnessDestinations[0].Position = 1
158                         },
159                         err: errPosition,
160                 },
161                 {
162                         desc: "mismatched mux dest value / output source value",
163                         f: func() {
164                                 outID := tx.ResultIds[0]
165                                 out := tx.Entries[*outID].(*bc.Output)
166                                 mux.WitnessDestinations[0].Value = &bc.AssetAmount{
167                                         AssetId: out.Source.Value.AssetId,
168                                         Amount:  out.Source.Value.Amount + 1,
169                                 }
170                                 mux.Sources[0].Value.Amount++ // the mux must still balance
171                         },
172                         err: errMismatchedValue,
173                 },
174                 {
175                         desc: "output exthash nonempty",
176                         f: func() {
177                                 tx.Entries[*tx.ResultIds[0]].(*bc.Output).ExtHash = newHash(1)
178                         },
179                         err: errNonemptyExtHash,
180                 },
181                 {
182                         desc: "output exthash nonempty, but that's OK",
183                         f: func() {
184                                 tx.Version = 2
185                                 tx.Entries[*tx.ResultIds[0]].(*bc.Output).ExtHash = newHash(1)
186                         },
187                 },
188                 {
189                         desc: "empty tx results",
190                         f: func() {
191                                 tx.ResultIds = nil
192                         },
193                         err: errEmptyResults,
194                 },
195                 {
196                         desc: "empty tx results, but that's OK",
197                         f: func() {
198                                 tx.Version = 2
199                                 tx.ResultIds = nil
200                         },
201                 },
202                 {
203                         desc: "tx header exthash nonempty",
204                         f: func() {
205                                 tx.ExtHash = newHash(1)
206                         },
207                         err: errNonemptyExtHash,
208                 },
209                 {
210                         desc: "tx header exthash nonempty, but that's OK",
211                         f: func() {
212                                 tx.Version = 2
213                                 tx.ExtHash = newHash(1)
214                         },
215                 },
216                 {
217                         desc: "issuance program failure",
218                         f: func() {
219                                 iss := txIssuance(t, tx, 0)
220                                 iss.WitnessArguments[0] = []byte{}
221                         },
222                         err: vm.ErrFalseVMResult,
223                 },
224                 {
225                         desc: "issuance exthash nonempty",
226                         f: func() {
227                                 iss := txIssuance(t, tx, 0)
228                                 iss.ExtHash = newHash(1)
229                         },
230                         err: errNonemptyExtHash,
231                 },
232                 {
233                         desc: "issuance exthash nonempty, but that's OK",
234                         f: func() {
235                                 tx.Version = 2
236                                 iss := txIssuance(t, tx, 0)
237                                 iss.ExtHash = newHash(1)
238                         },
239                 },
240                 {
241                         desc: "spend control program failure",
242                         f: func() {
243                                 spend := txSpend(t, tx, 1)
244                                 spend.WitnessArguments[0] = []byte{}
245                         },
246                         err: vm.ErrFalseVMResult,
247                 },
248                 {
249                         desc: "mismatched spent source/witness value",
250                         f: func() {
251                                 spend := txSpend(t, tx, 1)
252                                 spentOutput := tx.Entries[*spend.SpentOutputId].(*bc.Output)
253                                 spentOutput.Source.Value = &bc.AssetAmount{
254                                         AssetId: spend.WitnessDestination.Value.AssetId,
255                                         Amount:  spend.WitnessDestination.Value.Amount + 1,
256                                 }
257                         },
258                         err: errMismatchedValue,
259                 },
260                 {
261                         desc: "spend exthash nonempty",
262                         f: func() {
263                                 spend := txSpend(t, tx, 1)
264                                 spend.ExtHash = newHash(1)
265                         },
266                         err: errNonemptyExtHash,
267                 },
268                 {
269                         desc: "spend exthash nonempty, but that's OK",
270                         f: func() {
271                                 tx.Version = 2
272                                 spend := txSpend(t, tx, 1)
273                                 spend.ExtHash = newHash(1)
274                         },
275                 },
276         }
277
278         for _, c := range cases {
279                 t.Run(c.desc, func(t *testing.T) {
280                         fixture = sample(t, nil)
281                         tx = legacy.NewTx(*fixture.tx).Tx
282                         vs = &validationState{
283                                 block:   mockBlock(),
284                                 tx:      tx,
285                                 entryID: tx.ID,
286                                 gas: &gasState{
287                                         gasLeft: int64(80000),
288                                         gasUsed: 0,
289                                 },
290                                 cache: make(map[bc.Hash]error),
291                         }
292                         out := tx.Entries[*tx.ResultIds[0]].(*bc.Output)
293                         muxID := out.Source.Ref
294                         mux = tx.Entries[*muxID].(*bc.Mux)
295
296                         if c.f != nil {
297                                 c.f()
298                         }
299                         err := checkValid(vs, tx.TxHeader)
300
301                         if rootErr(err) != c.err {
302                                 t.Errorf("got error %s, want %s; validationState is:\n%s", err, c.err, spew.Sdump(vs))
303                         }
304                 })
305         }
306 }
307
308 func TestBlockHeaderValid(t *testing.T) {
309         base := bc.NewBlockHeader(1, 1, &bc.Hash{}, 1, &bc.Hash{}, &bc.Hash{}, 0, 0)
310         baseBytes, _ := proto.Marshal(base)
311
312         var bh bc.BlockHeader
313
314         cases := []struct {
315                 f   func()
316                 err error
317         }{
318                 {},
319                 {
320                         f: func() {
321                                 bh.Version = 2
322                         },
323                 },
324         }
325
326         for i, c := range cases {
327                 t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) {
328                         proto.Unmarshal(baseBytes, &bh)
329                         if c.f != nil {
330                                 c.f()
331                         }
332                 })
333         }
334 }
335
336 // A txFixture is returned by sample (below) to produce a sample
337 // transaction, which takes a separate, optional _input_ txFixture to
338 // affect the transaction that's built. The components of the
339 // transaction are the fields of txFixture.
340 type txFixture struct {
341         initialBlockID       bc.Hash
342         issuanceProg         bc.Program
343         issuanceArgs         [][]byte
344         assetDef             []byte
345         assetID              bc.AssetID
346         txVersion            uint64
347         txInputs             []*legacy.TxInput
348         txOutputs            []*legacy.TxOutput
349         txMinTime, txMaxTime uint64
350         txRefData            []byte
351         tx                   *legacy.TxData
352 }
353
354 // Produces a sample transaction in a txFixture object (see above). A
355 // separate input txFixture can be used to alter the transaction
356 // that's created.
357 //
358 // The output of this function can be used as the input to a
359 // subsequent call to make iterative refinements to a test object.
360 //
361 // The default transaction produced is valid and has three inputs:
362 //  - an issuance of 10 units
363 //  - a spend of 20 units
364 //  - a spend of 40 units
365 // and two outputs, one of 25 units and one of 45 units.
366 // All amounts are denominated in the same asset.
367 //
368 // The issuance program for the asset requires two numbers as
369 // arguments that add up to 5. The prevout control programs require
370 // two numbers each, adding to 9 and 13, respectively.
371 //
372 // The min and max times for the transaction are now +/- one minute.
373 func sample(tb testing.TB, in *txFixture) *txFixture {
374         var result txFixture
375         if in != nil {
376                 result = *in
377         }
378
379         if result.initialBlockID.IsZero() {
380                 result.initialBlockID = *newHash(1)
381         }
382         if testutil.DeepEqual(result.issuanceProg, bc.Program{}) {
383                 prog, err := vm.Assemble("ADD 5 NUMEQUAL")
384                 if err != nil {
385                         tb.Fatal(err)
386                 }
387                 result.issuanceProg = bc.Program{VmVersion: 1, Code: prog}
388         }
389         if len(result.issuanceArgs) == 0 {
390                 result.issuanceArgs = [][]byte{[]byte{2}, []byte{3}}
391         }
392         if len(result.assetDef) == 0 {
393                 result.assetDef = []byte{2}
394         }
395         if result.assetID.IsZero() {
396                 refdatahash := hashData(result.assetDef)
397                 result.assetID = bc.ComputeAssetID(result.issuanceProg.Code, &result.initialBlockID, result.issuanceProg.VmVersion, &refdatahash)
398         }
399
400         if result.txVersion == 0 {
401                 result.txVersion = 1
402         }
403         if len(result.txInputs) == 0 {
404                 cp1, err := vm.Assemble("ADD 9 NUMEQUAL")
405                 if err != nil {
406                         tb.Fatal(err)
407                 }
408                 args1 := [][]byte{[]byte{4}, []byte{5}}
409
410                 cp2, err := vm.Assemble("ADD 13 NUMEQUAL")
411                 if err != nil {
412                         tb.Fatal(err)
413                 }
414                 args2 := [][]byte{[]byte{6}, []byte{7}}
415
416                 result.txInputs = []*legacy.TxInput{
417                         legacy.NewIssuanceInput([]byte{3}, 10, []byte{4}, result.initialBlockID, result.issuanceProg.Code, result.issuanceArgs, result.assetDef),
418                         legacy.NewSpendInput(args1, *newHash(5), result.assetID, 20, 0, cp1, *newHash(6), []byte{7}),
419                         legacy.NewSpendInput(args2, *newHash(8), result.assetID, 40, 0, cp2, *newHash(9), []byte{10}),
420                 }
421         }
422
423         result.txInputs = append(result.txInputs, mockGasTxInput())
424
425         if len(result.txOutputs) == 0 {
426                 cp1, err := vm.Assemble("ADD 17 NUMEQUAL")
427                 if err != nil {
428                         tb.Fatal(err)
429                 }
430                 cp2, err := vm.Assemble("ADD 21 NUMEQUAL")
431                 if err != nil {
432                         tb.Fatal(err)
433                 }
434
435                 result.txOutputs = []*legacy.TxOutput{
436                         legacy.NewTxOutput(result.assetID, 25, cp1, []byte{11}),
437                         legacy.NewTxOutput(result.assetID, 45, cp2, []byte{12}),
438                 }
439         }
440         if result.txMinTime == 0 {
441                 result.txMinTime = bc.Millis(time.Now().Add(-time.Minute))
442         }
443         if result.txMaxTime == 0 {
444                 result.txMaxTime = bc.Millis(time.Now().Add(time.Minute))
445         }
446         if len(result.txRefData) == 0 {
447                 result.txRefData = []byte{13}
448         }
449
450         result.tx = &legacy.TxData{
451                 Version:       result.txVersion,
452                 Inputs:        result.txInputs,
453                 Outputs:       result.txOutputs,
454                 MinTime:       result.txMinTime,
455                 MaxTime:       result.txMaxTime,
456                 ReferenceData: result.txRefData,
457         }
458
459         return &result
460 }
461
462 func mockBlock() *bc.Block {
463         return &bc.Block{
464                 BlockHeader: &bc.BlockHeader{
465                         Height: 666,
466                 },
467         }
468 }
469
470 func mockGasTxInput() *legacy.TxInput {
471         return legacy.NewSpendInput([][]byte{}, *newHash(8), *validation.BTMAssetID, 100000000, 0, []byte{byte(vm.OP_TRUE)}, *newHash(9), []byte{})
472 }
473
474 // Like errors.Root, but also unwraps vm.Error objects.
475 func rootErr(e error) error {
476         for {
477                 e = errors.Root(e)
478                 if e2, ok := e.(vm.Error); ok {
479                         e = e2.Err
480                         continue
481                 }
482                 return e
483         }
484 }
485
486 func hashData(data []byte) bc.Hash {
487         var b32 [32]byte
488         sha3pool.Sum256(b32[:], data)
489         return bc.NewHash(b32)
490 }
491
492 func newHash(n byte) *bc.Hash {
493         h := bc.NewHash([32]byte{n})
494         return &h
495 }
496
497 func newAssetID(n byte) *bc.AssetID {
498         a := bc.NewAssetID([32]byte{n})
499         return &a
500 }
501
502 func txIssuance(t *testing.T, tx *bc.Tx, index int) *bc.Issuance {
503         id := tx.InputIDs[index]
504         res, err := tx.Issuance(id)
505         if err != nil {
506                 t.Fatal(err)
507         }
508         return res
509 }
510
511 func txSpend(t *testing.T, tx *bc.Tx, index int) *bc.Spend {
512         id := tx.InputIDs[index]
513         res, err := tx.Spend(id)
514         if err != nil {
515                 t.Fatal(err)
516         }
517         return res
518 }