OSDN Git Service

merge with master
[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/bctest"
13         "github.com/bytom/protocol/bc/legacy"
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: "nonce timerange misordered",
132                         f: func() {
133                                 iss := txIssuance(t, tx, 0)
134                                 nonce := tx.Entries[*iss.AnchorId].(*bc.Nonce)
135                                 tr := tx.Entries[*nonce.TimeRangeId].(*bc.TimeRange)
136                                 tr.MinTimeMs = tr.MaxTimeMs + 1
137                         },
138                         err: errBadTimeRange,
139                 },
140                 {
141                         desc: "nonce timerange disagrees with tx timerange",
142                         f: func() {
143                                 iss := txIssuance(t, tx, 0)
144                                 nonce := tx.Entries[*iss.AnchorId].(*bc.Nonce)
145                                 tr := tx.Entries[*nonce.TimeRangeId].(*bc.TimeRange)
146                                 tr.MaxTimeMs = tx.MaxTimeMs - 1
147                         },
148                         err: errBadTimeRange,
149                 },
150                 {
151                         desc: "nonce timerange exthash nonempty",
152                         f: func() {
153                                 iss := txIssuance(t, tx, 0)
154                                 nonce := tx.Entries[*iss.AnchorId].(*bc.Nonce)
155                                 tr := tx.Entries[*nonce.TimeRangeId].(*bc.TimeRange)
156                                 tr.ExtHash = newHash(1)
157                         },
158                         err: errNonemptyExtHash,
159                 },
160                 {
161                         desc: "nonce timerange exthash nonempty, but that's OK",
162                         f: func() {
163                                 tx.Version = 2
164                                 iss := txIssuance(t, tx, 0)
165                                 nonce := tx.Entries[*iss.AnchorId].(*bc.Nonce)
166                                 tr := tx.Entries[*nonce.TimeRangeId].(*bc.TimeRange)
167                                 tr.ExtHash = newHash(1)
168                         },
169                 },
170                 {
171                         desc: "mismatched output source / mux dest position",
172                         f: func() {
173                                 tx.Entries[*tx.ResultIds[0]].(*bc.Output).Source.Position = 1
174                         },
175                         err: errMismatchedPosition,
176                 },
177                 {
178                         desc: "mismatched output source and mux dest",
179                         f: func() {
180                                 // For this test, it's necessary to construct a mostly
181                                 // identical second transaction in order to get a similar but
182                                 // not equal output entry for the mux to falsely point
183                                 // to. That entry must be added to the first tx's Entries map.
184                                 fixture.txOutputs[0].ReferenceData = []byte{1}
185                                 fixture2 := sample(t, fixture)
186                                 tx2 := legacy.NewTx(*fixture2.tx).Tx
187                                 out2ID := tx2.ResultIds[0]
188                                 out2 := tx2.Entries[*out2ID].(*bc.Output)
189                                 tx.Entries[*out2ID] = out2
190                                 mux.WitnessDestinations[0].Ref = out2ID
191                         },
192                         err: errMismatchedReference,
193                 },
194                 {
195                         desc: "invalid mux destination position",
196                         f: func() {
197                                 mux.WitnessDestinations[0].Position = 1
198                         },
199                         err: errPosition,
200                 },
201                 {
202                         desc: "mismatched mux dest value / output source value",
203                         f: func() {
204                                 outID := tx.ResultIds[0]
205                                 out := tx.Entries[*outID].(*bc.Output)
206                                 mux.WitnessDestinations[0].Value = &bc.AssetAmount{
207                                         AssetId: out.Source.Value.AssetId,
208                                         Amount:  out.Source.Value.Amount + 1,
209                                 }
210                                 mux.Sources[0].Value.Amount++ // the mux must still balance
211                         },
212                         err: errMismatchedValue,
213                 },
214                 {
215                         desc: "output exthash nonempty",
216                         f: func() {
217                                 tx.Entries[*tx.ResultIds[0]].(*bc.Output).ExtHash = newHash(1)
218                         },
219                         err: errNonemptyExtHash,
220                 },
221                 {
222                         desc: "output exthash nonempty, but that's OK",
223                         f: func() {
224                                 tx.Version = 2
225                                 tx.Entries[*tx.ResultIds[0]].(*bc.Output).ExtHash = newHash(1)
226                         },
227                 },
228                 {
229                         desc: "misordered tx time range",
230                         f: func() {
231                                 tx.MinTimeMs = tx.MaxTimeMs + 1
232                         },
233                         err: errBadTimeRange,
234                 },
235                 {
236                         desc: "empty tx results",
237                         f: func() {
238                                 tx.ResultIds = nil
239                         },
240                         err: errEmptyResults,
241                 },
242                 {
243                         desc: "empty tx results, but that's OK",
244                         f: func() {
245                                 tx.Version = 2
246                                 tx.ResultIds = nil
247                         },
248                 },
249                 {
250                         desc: "tx header exthash nonempty",
251                         f: func() {
252                                 tx.ExtHash = newHash(1)
253                         },
254                         err: errNonemptyExtHash,
255                 },
256                 {
257                         desc: "tx header exthash nonempty, but that's OK",
258                         f: func() {
259                                 tx.Version = 2
260                                 tx.ExtHash = newHash(1)
261                         },
262                 },
263                 {
264                         desc: "wrong blockchain",
265                         f: func() {
266                                 vs.blockchainID = *newHash(2)
267                         },
268                         err: errWrongBlockchain,
269                 },
270                 {
271                         desc: "issuance program failure",
272                         f: func() {
273                                 iss := txIssuance(t, tx, 0)
274                                 iss.WitnessArguments[0] = []byte{}
275                         },
276                         err: vm.ErrFalseVMResult,
277                 },
278                 {
279                         desc: "issuance exthash nonempty",
280                         f: func() {
281                                 iss := txIssuance(t, tx, 0)
282                                 iss.ExtHash = newHash(1)
283                         },
284                         err: errNonemptyExtHash,
285                 },
286                 {
287                         desc: "issuance exthash nonempty, but that's OK",
288                         f: func() {
289                                 tx.Version = 2
290                                 iss := txIssuance(t, tx, 0)
291                                 iss.ExtHash = newHash(1)
292                         },
293                 },
294                 {
295                         desc: "spend control program failure",
296                         f: func() {
297                                 spend := txSpend(t, tx, 1)
298                                 spend.WitnessArguments[0] = []byte{}
299                         },
300                         err: vm.ErrFalseVMResult,
301                 },
302                 {
303                         desc: "mismatched spent source/witness value",
304                         f: func() {
305                                 spend := txSpend(t, tx, 1)
306                                 spentOutput := tx.Entries[*spend.SpentOutputId].(*bc.Output)
307                                 spentOutput.Source.Value = &bc.AssetAmount{
308                                         AssetId: spend.WitnessDestination.Value.AssetId,
309                                         Amount:  spend.WitnessDestination.Value.Amount + 1,
310                                 }
311                         },
312                         err: errMismatchedValue,
313                 },
314                 {
315                         desc: "spend exthash nonempty",
316                         f: func() {
317                                 spend := txSpend(t, tx, 1)
318                                 spend.ExtHash = newHash(1)
319                         },
320                         err: errNonemptyExtHash,
321                 },
322                 {
323                         desc: "spend exthash nonempty, but that's OK",
324                         f: func() {
325                                 tx.Version = 2
326                                 spend := txSpend(t, tx, 1)
327                                 spend.ExtHash = newHash(1)
328                         },
329                 },
330         }
331
332         for _, c := range cases {
333                 t.Run(c.desc, func(t *testing.T) {
334                         fixture = sample(t, nil)
335                         tx = legacy.NewTx(*fixture.tx).Tx
336                         vs = &validationState{
337                                 blockchainID: fixture.initialBlockID,
338                                 tx:           tx,
339                                 entryID:      tx.ID,
340                                 gas: &gasState{
341                                         gasLeft: uint64(1000),
342                                         gasUsed: 0,
343                                         maxGas:  uint64(1000),
344                                 },
345                                 cache: make(map[bc.Hash]error),
346                         }
347                         out := tx.Entries[*tx.ResultIds[0]].(*bc.Output)
348                         muxID := out.Source.Ref
349                         mux = tx.Entries[*muxID].(*bc.Mux)
350
351                         if c.f != nil {
352                                 c.f()
353                         }
354                         err := checkValid(vs, tx.TxHeader)
355                         if rootErr(err) != c.err {
356                                 t.Errorf("got error %s, want %s; validationState is:\n%s", err, c.err, spew.Sdump(vs))
357                         }
358                 })
359         }
360 }
361
362 func TestNoncelessIssuance(t *testing.T) {
363         tx := bctest.NewIssuanceTx(t, bc.EmptyStringHash, func(tx *legacy.Tx) {
364                 // Remove the issuance nonce.
365                 tx.Inputs[0].TypedInput.(*legacy.IssuanceInput).Nonce = nil
366         })
367
368         _, err := ValidateTx(legacy.MapTx(&tx.TxData), bc.EmptyStringHash)
369         if errors.Root(err) != bc.ErrMissingEntry {
370                 t.Fatalf("got %s, want %s", err, bc.ErrMissingEntry)
371         }
372 }
373
374 func TestBlockHeaderValid(t *testing.T) {
375         base := bc.NewBlockHeader(1, 1, &bc.Hash{}, 1, &bc.Hash{}, &bc.Hash{}, 0, 0)
376         baseBytes, _ := proto.Marshal(base)
377
378         var bh bc.BlockHeader
379
380         cases := []struct {
381                 f   func()
382                 err error
383         }{
384                 {},
385                 {
386                         f: func() {
387                                 bh.Version = 2
388                         },
389                 },
390         }
391
392         for i, c := range cases {
393                 t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) {
394                         proto.Unmarshal(baseBytes, &bh)
395                         if c.f != nil {
396                                 c.f()
397                         }
398                 })
399         }
400 }
401
402 // A txFixture is returned by sample (below) to produce a sample
403 // transaction, which takes a separate, optional _input_ txFixture to
404 // affect the transaction that's built. The components of the
405 // transaction are the fields of txFixture.
406 type txFixture struct {
407         initialBlockID       bc.Hash
408         issuanceProg         bc.Program
409         issuanceArgs         [][]byte
410         assetDef             []byte
411         assetID              bc.AssetID
412         txVersion            uint64
413         txInputs             []*legacy.TxInput
414         txOutputs            []*legacy.TxOutput
415         txMinTime, txMaxTime uint64
416         txRefData            []byte
417         tx                   *legacy.TxData
418 }
419
420 // Produces a sample transaction in a txFixture object (see above). A
421 // separate input txFixture can be used to alter the transaction
422 // that's created.
423 //
424 // The output of this function can be used as the input to a
425 // subsequent call to make iterative refinements to a test object.
426 //
427 // The default transaction produced is valid and has three inputs:
428 //  - an issuance of 10 units
429 //  - a spend of 20 units
430 //  - a spend of 40 units
431 // and two outputs, one of 25 units and one of 45 units.
432 // All amounts are denominated in the same asset.
433 //
434 // The issuance program for the asset requires two numbers as
435 // arguments that add up to 5. The prevout control programs require
436 // two numbers each, adding to 9 and 13, respectively.
437 //
438 // The min and max times for the transaction are now +/- one minute.
439 func sample(tb testing.TB, in *txFixture) *txFixture {
440         var result txFixture
441         if in != nil {
442                 result = *in
443         }
444
445         if result.initialBlockID.IsZero() {
446                 result.initialBlockID = *newHash(1)
447         }
448         if testutil.DeepEqual(result.issuanceProg, bc.Program{}) {
449                 prog, err := vm.Assemble("ADD 5 NUMEQUAL")
450                 if err != nil {
451                         tb.Fatal(err)
452                 }
453                 result.issuanceProg = bc.Program{VmVersion: 1, Code: prog}
454         }
455         if len(result.issuanceArgs) == 0 {
456                 result.issuanceArgs = [][]byte{[]byte{2}, []byte{3}}
457         }
458         if len(result.assetDef) == 0 {
459                 result.assetDef = []byte{2}
460         }
461         if result.assetID.IsZero() {
462                 refdatahash := hashData(result.assetDef)
463                 result.assetID = bc.ComputeAssetID(result.issuanceProg.Code, &result.initialBlockID, result.issuanceProg.VmVersion, &refdatahash)
464         }
465
466         if result.txVersion == 0 {
467                 result.txVersion = 1
468         }
469         if len(result.txInputs) == 0 {
470                 cp1, err := vm.Assemble("ADD 9 NUMEQUAL")
471                 if err != nil {
472                         tb.Fatal(err)
473                 }
474                 args1 := [][]byte{[]byte{4}, []byte{5}}
475
476                 cp2, err := vm.Assemble("ADD 13 NUMEQUAL")
477                 if err != nil {
478                         tb.Fatal(err)
479                 }
480                 args2 := [][]byte{[]byte{6}, []byte{7}}
481
482                 result.txInputs = []*legacy.TxInput{
483                         legacy.NewIssuanceInput([]byte{3}, 10, []byte{4}, result.initialBlockID, result.issuanceProg.Code, result.issuanceArgs, result.assetDef),
484                         legacy.NewSpendInput(args1, *newHash(5), result.assetID, 20, 0, cp1, *newHash(6), []byte{7}),
485                         legacy.NewSpendInput(args2, *newHash(8), result.assetID, 40, 0, cp2, *newHash(9), []byte{10}),
486                 }
487         }
488         if len(result.txOutputs) == 0 {
489                 cp1, err := vm.Assemble("ADD 17 NUMEQUAL")
490                 if err != nil {
491                         tb.Fatal(err)
492                 }
493                 cp2, err := vm.Assemble("ADD 21 NUMEQUAL")
494                 if err != nil {
495                         tb.Fatal(err)
496                 }
497
498                 result.txOutputs = []*legacy.TxOutput{
499                         legacy.NewTxOutput(result.assetID, 25, cp1, []byte{11}),
500                         legacy.NewTxOutput(result.assetID, 45, cp2, []byte{12}),
501                 }
502         }
503         if result.txMinTime == 0 {
504                 result.txMinTime = bc.Millis(time.Now().Add(-time.Minute))
505         }
506         if result.txMaxTime == 0 {
507                 result.txMaxTime = bc.Millis(time.Now().Add(time.Minute))
508         }
509         if len(result.txRefData) == 0 {
510                 result.txRefData = []byte{13}
511         }
512
513         result.tx = &legacy.TxData{
514                 Version:       result.txVersion,
515                 Inputs:        result.txInputs,
516                 Outputs:       result.txOutputs,
517                 MinTime:       result.txMinTime,
518                 MaxTime:       result.txMaxTime,
519                 ReferenceData: result.txRefData,
520         }
521
522         return &result
523 }
524
525 // Like errors.Root, but also unwraps vm.Error objects.
526 func rootErr(e error) error {
527         for {
528                 e = errors.Root(e)
529                 if e2, ok := e.(vm.Error); ok {
530                         e = e2.Err
531                         continue
532                 }
533                 return e
534         }
535 }
536
537 func hashData(data []byte) bc.Hash {
538         var b32 [32]byte
539         sha3pool.Sum256(b32[:], data)
540         return bc.NewHash(b32)
541 }
542
543 func newHash(n byte) *bc.Hash {
544         h := bc.NewHash([32]byte{n})
545         return &h
546 }
547
548 func newAssetID(n byte) *bc.AssetID {
549         a := bc.NewAssetID([32]byte{n})
550         return &a
551 }
552
553 func txIssuance(t *testing.T, tx *bc.Tx, index int) *bc.Issuance {
554         id := tx.InputIDs[index]
555         res, err := tx.Issuance(id)
556         if err != nil {
557                 t.Fatal(err)
558         }
559         return res
560 }
561
562 func txSpend(t *testing.T, tx *bc.Tx, index int) *bc.Spend {
563         id := tx.InputIDs[index]
564         res, err := tx.Spend(id)
565         if err != nil {
566                 t.Fatal(err)
567         }
568         return res
569 }