This repository has been archived by the owner on Mar 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 358
/
validation.go
595 lines (507 loc) · 17.4 KB
/
validation.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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
package validation
import (
"fmt"
"github.com/bytom/consensus"
"github.com/bytom/errors"
"github.com/bytom/math/checked"
"github.com/bytom/protocol/bc"
"github.com/bytom/protocol/vm"
)
const (
defaultGasLimit = int64(80000)
muxGasCost = int64(10)
gasRate = int64(1000)
)
type gasState struct {
gasLeft int64
gasUsed int64
BTMValue int64
}
func (g *gasState) setGas(BTMValue int64) error {
if BTMValue < 0 {
return errGasCalculate
}
g.BTMValue = BTMValue
if gasAmount, ok := checked.DivInt64(BTMValue, gasRate); ok {
if gasAmount == 0 {
g.gasLeft = muxGasCost
} else if gasAmount < defaultGasLimit {
g.gasLeft = gasAmount
}
} else {
return errGasCalculate
}
return nil
}
func (g *gasState) updateUsage(gasLeft int64) error {
if gasLeft < 0 {
return errGasCalculate
}
if gasUsed, ok := checked.SubInt64(g.gasLeft, gasLeft); ok {
g.gasUsed += gasUsed
g.gasLeft = gasLeft
} else {
return errGasCalculate
}
return nil
}
// validationState contains the context that must propagate through
// the transaction graph when validating entries.
type validationState struct {
// The ID of the blockchain
block *bc.Block
// The enclosing transaction object
tx *bc.Tx
// The ID of the nearest enclosing entry
entryID bc.Hash
// The source position, for validating ValueSources
sourcePos uint64
// The destination position, for validating ValueDestinations
destPos uint64
// Memoized per-entry validation results
cache map[bc.Hash]error
gas *gasState
}
var (
errGasCalculate = errors.New("gas usage calculate got a math error")
errEmptyResults = errors.New("transaction has no results")
errMismatchedAssetID = errors.New("mismatched asset id")
errMismatchedBlock = errors.New("mismatched block")
errMismatchedMerkleRoot = errors.New("mismatched merkle root")
errMismatchedPosition = errors.New("mismatched value source/dest positions")
errMismatchedReference = errors.New("mismatched reference")
errMismatchedValue = errors.New("mismatched value")
errMisorderedBlockHeight = errors.New("misordered block height")
errMisorderedBlockTime = errors.New("misordered block time")
errMissingField = errors.New("missing required field")
errNoGas = errors.New("no gas input")
errNoPrevBlock = errors.New("no previous block")
errNoSource = errors.New("no source for value")
errNonemptyExtHash = errors.New("non-empty extension hash")
errOverflow = errors.New("arithmetic overflow/underflow")
errPosition = errors.New("invalid source or destination position")
errWorkProof = errors.New("invalid difficulty proof of work")
errTxVersion = errors.New("invalid transaction version")
errUnbalanced = errors.New("unbalanced")
errUntimelyTransaction = errors.New("block timestamp outside transaction time range")
errVersionRegression = errors.New("version regression")
errWrongBlockSize = errors.New("block size is too big")
errWrongTransactionSize = errors.New("transaction size is too big")
errWrongCoinbaseTransaction = errors.New("wrong coinbase transaction")
errWrongCoinbaseAsset = errors.New("wrong coinbase asset id")
)
func checkValid(vs *validationState, e bc.Entry) (err error) {
entryID := bc.EntryID(e)
var ok bool
if err, ok = vs.cache[entryID]; ok {
return err
}
defer func() {
vs.cache[entryID] = err
}()
switch e := e.(type) {
case *bc.TxHeader:
for i, resID := range e.ResultIds {
resultEntry := vs.tx.Entries[*resID]
vs2 := *vs
vs2.entryID = *resID
err = checkValid(&vs2, resultEntry)
if err != nil {
return errors.Wrapf(err, "checking result %d", i)
}
}
if e.Version == 1 {
if len(e.ResultIds) == 0 {
return errEmptyResults
}
if e.ExtHash != nil && !e.ExtHash.IsZero() {
return errNonemptyExtHash
}
}
case *bc.Coinbase:
if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
return errWrongCoinbaseTransaction
}
if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
return errWrongCoinbaseAsset
}
vs2 := *vs
vs2.destPos = 0
err = checkValidDest(&vs2, e.WitnessDestination)
if err != nil {
return errors.Wrap(err, "checking coinbase destination")
}
case *bc.Mux:
parity := make(map[bc.AssetID]int64)
for i, src := range e.Sources {
sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
if !ok {
return errors.WithDetailf(errOverflow, "adding %d units of asset %x from mux source %d to total %d overflows int64", src.Value.Amount, src.Value.AssetId.Bytes(), i, parity[*src.Value.AssetId])
}
parity[*src.Value.AssetId] = sum
}
for i, dest := range e.WitnessDestinations {
sum, ok := parity[*dest.Value.AssetId]
if !ok {
return errors.WithDetailf(errNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
}
diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
if !ok {
return errors.WithDetailf(errOverflow, "subtracting %d units of asset %x from mux destination %d from total %d underflows int64", dest.Value.Amount, dest.Value.AssetId.Bytes(), i, sum)
}
parity[*dest.Value.AssetId] = diff
}
if amount, ok := parity[*consensus.BTMAssetID]; ok {
if err = vs.gas.setGas(amount); err != nil {
return err
}
} else {
vs.gas.setGas(0)
}
for assetID, amount := range parity {
if amount != 0 && assetID != *consensus.BTMAssetID {
return errors.WithDetailf(errUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
}
}
gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.Program, e.WitnessArguments), vs.gas.gasLeft)
if err != nil {
return errors.Wrap(err, "checking mux program")
}
if err = vs.gas.updateUsage(gasLeft); err != nil {
return err
}
for i, src := range e.Sources {
vs2 := *vs
vs2.sourcePos = uint64(i)
err = checkValidSrc(&vs2, src)
if err != nil {
return errors.Wrapf(err, "checking mux source %d", i)
}
}
for i, dest := range e.WitnessDestinations {
vs2 := *vs
vs2.destPos = uint64(i)
err = checkValidDest(&vs2, dest)
if err != nil {
return errors.Wrapf(err, "checking mux destination %d", i)
}
}
if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
return errNonemptyExtHash
}
case *bc.Nonce:
//TODO: add block heigh range check on the control program
gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.Program, e.WitnessArguments), vs.gas.gasLeft)
if err != nil {
return errors.Wrap(err, "checking nonce program")
}
if err = vs.gas.updateUsage(gasLeft); err != nil {
return err
}
if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
return errNonemptyExtHash
}
case *bc.Output:
vs2 := *vs
vs2.sourcePos = 0
err = checkValidSrc(&vs2, e.Source)
if err != nil {
return errors.Wrap(err, "checking output source")
}
if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
return errNonemptyExtHash
}
case *bc.Retirement:
vs2 := *vs
vs2.sourcePos = 0
err = checkValidSrc(&vs2, e.Source)
if err != nil {
return errors.Wrap(err, "checking retirement source")
}
if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
return errNonemptyExtHash
}
case *bc.Issuance:
computedAssetID := e.WitnessAssetDefinition.ComputeAssetID()
if computedAssetID != *e.Value.AssetId {
return errors.WithDetailf(errMismatchedAssetID, "asset ID is %x, issuance wants %x", computedAssetID.Bytes(), e.Value.AssetId.Bytes())
}
anchor, ok := vs.tx.Entries[*e.AnchorId]
if !ok {
return errors.Wrapf(bc.ErrMissingEntry, "entry for issuance anchor %x not found", e.AnchorId.Bytes())
}
gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.WitnessAssetDefinition.IssuanceProgram, e.WitnessArguments), vs.gas.gasLeft)
if err != nil {
return errors.Wrap(err, "checking issuance program")
}
if err = vs.gas.updateUsage(gasLeft); err != nil {
return err
}
var anchored *bc.Hash
switch a := anchor.(type) {
case *bc.Nonce:
anchored = a.WitnessAnchoredId
case *bc.Spend:
anchored = a.WitnessAnchoredId
case *bc.Issuance:
anchored = a.WitnessAnchoredId
default:
return errors.WithDetailf(bc.ErrEntryType, "issuance anchor has type %T, should be nonce, spend, or issuance", anchor)
}
if *anchored != vs.entryID {
return errors.WithDetailf(errMismatchedReference, "issuance %x anchor is for %x", vs.entryID.Bytes(), anchored.Bytes())
}
anchorVS := *vs
anchorVS.entryID = *e.AnchorId
err = checkValid(&anchorVS, anchor)
if err != nil {
return errors.Wrap(err, "checking issuance anchor")
}
destVS := *vs
destVS.destPos = 0
err = checkValidDest(&destVS, e.WitnessDestination)
if err != nil {
return errors.Wrap(err, "checking issuance destination")
}
if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
return errNonemptyExtHash
}
case *bc.Spend:
if e.SpentOutputId == nil {
return errors.Wrap(errMissingField, "spend without spent output ID")
}
spentOutput, err := vs.tx.Output(*e.SpentOutputId)
if err != nil {
return errors.Wrap(err, "getting spend prevout")
}
gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gas.gasLeft)
if err != nil {
return errors.Wrap(err, "checking control program")
}
if err = vs.gas.updateUsage(gasLeft); err != nil {
return err
}
eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
if err != nil {
return err
}
if !eq {
return errors.WithDetailf(
errMismatchedValue,
"previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
spentOutput.Source.Value.Amount,
spentOutput.Source.Value.AssetId.Bytes(),
e.WitnessDestination.Value.Amount,
e.WitnessDestination.Value.AssetId.Bytes(),
)
}
vs2 := *vs
vs2.destPos = 0
err = checkValidDest(&vs2, e.WitnessDestination)
if err != nil {
return errors.Wrap(err, "checking spend destination")
}
if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
return errNonemptyExtHash
}
default:
return fmt.Errorf("entry has unexpected type %T", e)
}
return nil
}
func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
if vs == nil {
return errors.Wrap(errMissingField, "empty value source")
}
if vs.Ref == nil {
return errors.Wrap(errMissingField, "missing ref on value source")
}
if vs.Value == nil || vs.Value.AssetId == nil {
return errors.Wrap(errMissingField, "missing value on value source")
}
e, ok := vstate.tx.Entries[*vs.Ref]
if !ok {
return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
}
vstate2 := *vstate
vstate2.entryID = *vs.Ref
err := checkValid(&vstate2, e)
if err != nil {
return errors.Wrap(err, "checking value source")
}
var dest *bc.ValueDestination
switch ref := e.(type) {
case *bc.Coinbase:
if vs.Position != 0 {
return errors.Wrapf(errPosition, "invalid position %d for coinbase source", vs.Position)
}
dest = ref.WitnessDestination
case *bc.Issuance:
if vs.Position != 0 {
return errors.Wrapf(errPosition, "invalid position %d for issuance source", vs.Position)
}
dest = ref.WitnessDestination
case *bc.Spend:
if vs.Position != 0 {
return errors.Wrapf(errPosition, "invalid position %d for spend source", vs.Position)
}
dest = ref.WitnessDestination
case *bc.Mux:
if vs.Position >= uint64(len(ref.WitnessDestinations)) {
return errors.Wrapf(errPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
}
dest = ref.WitnessDestinations[vs.Position]
default:
return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
}
if dest.Ref == nil || *dest.Ref != vstate.entryID {
return errors.Wrapf(errMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
}
if dest.Position != vstate.sourcePos {
return errors.Wrapf(errMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
}
eq, err := dest.Value.Equal(vs.Value)
if err != nil {
return errors.Sub(errMissingField, err)
}
if !eq {
return errors.Wrapf(errMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
}
return nil
}
func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
if vd == nil {
return errors.Wrap(errMissingField, "empty value destination")
}
if vd.Ref == nil {
return errors.Wrap(errMissingField, "missing ref on value destination")
}
if vd.Value == nil || vd.Value.AssetId == nil {
return errors.Wrap(errMissingField, "missing value on value source")
}
e, ok := vs.tx.Entries[*vd.Ref]
if !ok {
return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
}
var src *bc.ValueSource
switch ref := e.(type) {
case *bc.Output:
if vd.Position != 0 {
return errors.Wrapf(errPosition, "invalid position %d for output destination", vd.Position)
}
src = ref.Source
case *bc.Retirement:
if vd.Position != 0 {
return errors.Wrapf(errPosition, "invalid position %d for retirement destination", vd.Position)
}
src = ref.Source
case *bc.Mux:
if vd.Position >= uint64(len(ref.Sources)) {
return errors.Wrapf(errPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
}
src = ref.Sources[vd.Position]
default:
return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
}
if src.Ref == nil || *src.Ref != vs.entryID {
return errors.Wrapf(errMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
}
if src.Position != vs.destPos {
return errors.Wrapf(errMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
}
eq, err := src.Value.Equal(vd.Value)
if err != nil {
return errors.Sub(errMissingField, err)
}
if !eq {
return errors.Wrapf(errMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
}
return nil
}
// ValidateBlock validates a block and the transactions within.
// It does not run the consensus program; for that, see ValidateBlockSig.
func ValidateBlock(b, prev *bc.Block) error {
if b.Height > 1 {
if prev == nil {
return errors.WithDetailf(errNoPrevBlock, "height %d", b.Height)
}
err := validateBlockAgainstPrev(b, prev)
if err != nil {
return err
}
}
if b.BlockHeader.SerializedSize > consensus.MaxBlockSzie {
return errWrongBlockSize
}
if !consensus.CheckProofOfWork(&b.ID, b.BlockHeader.Bits) {
return errWorkProof
}
coinbaseValue := consensus.BlockSubsidy(b.BlockHeader.Height)
for i, tx := range b.Transactions {
if b.Version == 1 && tx.Version != 1 {
return errors.WithDetailf(errTxVersion, "block version %d, transaction version %d", b.Version, tx.Version)
}
if tx.MaxTimeMs > 0 && b.TimestampMs > tx.MaxTimeMs {
return errors.WithDetailf(errUntimelyTransaction, "block timestamp %d, transaction time range %d-%d", b.TimestampMs, tx.MinTimeMs, tx.MaxTimeMs)
}
if tx.MinTimeMs > 0 && b.TimestampMs > 0 && b.TimestampMs < tx.MinTimeMs {
return errors.WithDetailf(errUntimelyTransaction, "block timestamp %d, transaction time range %d-%d", b.TimestampMs, tx.MinTimeMs, tx.MaxTimeMs)
}
txBTMValue, err := ValidateTx(tx, b)
if err != nil {
return errors.Wrapf(err, "validity of transaction %d of %d", i, len(b.Transactions))
}
coinbaseValue += txBTMValue
}
// check the coinbase output entry value
cbTx := b.Transactions[0]
cbOutput := cbTx.Entries[*cbTx.TxHeader.ResultIds[0]]
if cbOutput, ok := cbOutput.(*bc.Output); ok {
if cbOutput.Source.Value.Amount != coinbaseValue {
return errWrongCoinbaseTransaction
}
} else {
return errWrongCoinbaseTransaction
}
txRoot, err := bc.MerkleRoot(b.Transactions)
if err != nil {
return errors.Wrap(err, "computing transaction merkle root")
}
if txRoot != *b.TransactionsRoot {
return errors.WithDetailf(errMismatchedMerkleRoot, "computed %x, current block wants %x", txRoot.Bytes(), b.TransactionsRoot.Bytes())
}
return nil
}
func validateBlockAgainstPrev(b, prev *bc.Block) error {
if b.Version < prev.Version {
return errors.WithDetailf(errVersionRegression, "previous block verson %d, current block version %d", prev.Version, b.Version)
}
if b.Height != prev.Height+1 {
return errors.WithDetailf(errMisorderedBlockHeight, "previous block height %d, current block height %d", prev.Height, b.Height)
}
if prev.ID != *b.PreviousBlockId {
return errors.WithDetailf(errMismatchedBlock, "previous block ID %x, current block wants %x", prev.ID.Bytes(), b.PreviousBlockId.Bytes())
}
if b.TimestampMs <= prev.TimestampMs {
return errors.WithDetailf(errMisorderedBlockTime, "previous block time %d, current block time %d", prev.TimestampMs, b.TimestampMs)
}
return nil
}
// ValidateTx validates a transaction.
func ValidateTx(tx *bc.Tx, block *bc.Block) (uint64, error) {
if tx.TxHeader.SerializedSize > consensus.MaxTxSize {
return 0, errWrongTransactionSize
}
//TODO: handle the gas limit
vs := &validationState{
block: block,
tx: tx,
entryID: tx.ID,
gas: &gasState{
gasLeft: defaultGasLimit,
},
cache: make(map[bc.Hash]error),
}
err := checkValid(vs, tx.TxHeader)
return uint64(vs.gas.BTMValue), err
}