/
utxoset.go
758 lines (687 loc) · 21.1 KB
/
utxoset.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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
// Copyright (c) 2018 ContentBox Authors.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package chain
import (
"errors"
"fmt"
"reflect"
"sync"
"github.com/BOXFoundation/boxd/core"
"github.com/BOXFoundation/boxd/core/txlogic"
"github.com/BOXFoundation/boxd/core/types"
state "github.com/BOXFoundation/boxd/core/worldstate"
"github.com/BOXFoundation/boxd/crypto"
"github.com/BOXFoundation/boxd/script"
"github.com/BOXFoundation/boxd/storage"
)
// UtxoSet contains all utxos
type UtxoSet struct {
utxoMap types.UtxoMap
normalTxUtxoSet map[types.OutPoint]struct{}
contractUtxos []*types.OutPoint
}
// BalanceChangeMap defines the balance changes of accounts (add or subtract)
type BalanceChangeMap map[types.AddressHash]uint64
// NewUtxoSet new utxo set
func NewUtxoSet() *UtxoSet {
return &UtxoSet{
utxoMap: make(types.UtxoMap),
normalTxUtxoSet: make(map[types.OutPoint]struct{}),
}
}
// NewUtxoSetFromMap returns the underlying utxos as a map
func NewUtxoSetFromMap(utxoMap types.UtxoMap) *UtxoSet {
return &UtxoSet{
utxoMap: utxoMap,
}
}
// GetUtxos returns the unspent utxos
func (u *UtxoSet) GetUtxos() types.UtxoMap {
result := make(types.UtxoMap)
for outPoint, utxoWrap := range u.utxoMap {
if !utxoWrap.IsSpent() {
result[outPoint] = utxoWrap
}
}
return result
}
// All returns all utxo contained including spent utxo
func (u *UtxoSet) All() types.UtxoMap {
return u.utxoMap
}
// ImportUtxoMap imports utxos from a UtxoMap
func (u *UtxoSet) ImportUtxoMap(m types.UtxoMap, overwrite bool) {
for op, um := range m {
if _, ok := u.utxoMap[op]; ok && !overwrite {
continue
}
u.utxoMap[op] = um
}
}
// FindUtxo returns information about an outpoint.
func (u *UtxoSet) FindUtxo(outPoint types.OutPoint) *types.UtxoWrap {
return u.utxoMap[outPoint]
}
// AddUtxo adds a tx's outputs as utxos
func (u *UtxoSet) AddUtxo(tx *types.Transaction, txOutIdx uint32, blockHeight uint32) error {
// Index out of bound
if txOutIdx >= uint32(len(tx.Vout)) {
return core.ErrTxOutIndexOob
}
txHash, _ := tx.TxHash()
vout := tx.Vout[txOutIdx]
sc := script.NewScriptFromBytes(vout.ScriptPubKey)
if sc.IsContractPubkey() { // smart contract utxo
return fmt.Errorf("UtxoSet AddUtxo: tx %s incluces a contract vout", txHash)
}
// common tx
var utxoWrap *types.UtxoWrap
outPoint := types.OutPoint{Hash: *txHash, Index: txOutIdx}
if utxoWrap = u.utxoMap[outPoint]; utxoWrap != nil {
return core.ErrAddExistingUtxo
}
utxoWrap = types.NewUtxoWrap(vout.Value, vout.ScriptPubKey, blockHeight)
if IsCoinBase(tx) {
utxoWrap.SetCoinBase()
}
u.utxoMap[outPoint] = utxoWrap
if !txlogic.HasContractVout(tx) {
u.normalTxUtxoSet[outPoint] = struct{}{}
}
return nil
}
// SpendUtxo mark a utxo as the spent state.
func (u *UtxoSet) SpendUtxo(outPoint types.OutPoint) {
utxoWrap := u.utxoMap[outPoint]
if utxoWrap == nil {
// Mark the utxo entry as spent so it could be deleted from db later
utxoWrap = &types.UtxoWrap{}
u.utxoMap[outPoint] = utxoWrap
}
utxoWrap.Spend()
}
// TxInputAmount returns total amount from tx's inputs
// Return 0 if a tx is not fully funded, i.e., if not all of its spending utxos exist
func (u *UtxoSet) TxInputAmount(tx *types.Transaction) uint64 {
totalInputAmount := uint64(0)
for _, txIn := range tx.Vin {
utxo := u.FindUtxo(txIn.PrevOutPoint)
if utxo == nil || utxo.IsSpent() {
return uint64(0)
}
totalInputAmount += utxo.Value()
}
return totalInputAmount
}
// GetExtendedTxUtxoSet returns tx's utxo set from both db & txs in spendableTxs
func GetExtendedTxUtxoSet(tx *types.Transaction, db storage.Table,
spendableTxs *sync.Map) (*UtxoSet, error) {
utxoSet := NewUtxoSet()
if err := utxoSet.LoadTxUtxos(tx, db); err != nil {
return nil, err
}
// Outputs of existing txs in spendableTxs can also be spent
for _, txIn := range tx.Vin {
utxo := utxoSet.FindUtxo(txIn.PrevOutPoint)
if utxo != nil && !utxo.IsSpent() {
continue
}
if v, exists := spendableTxs.Load(txIn.PrevOutPoint.Hash); exists {
spendableTxWrap := v.(*types.TxWrap)
if err := utxoSet.AddUtxo(spendableTxWrap.Tx, txIn.PrevOutPoint.Index,
spendableTxWrap.Height); err != nil {
logger.Error(err)
}
}
}
return utxoSet, nil
}
func (u *UtxoSet) applyUtxo(tx *types.Transaction, txOutIdx uint32, blockHeight uint32) error {
if txOutIdx >= uint32(len(tx.Vout)) {
return core.ErrTxOutIndexOob
}
txHash, _ := tx.TxHash()
vout := tx.Vout[txOutIdx]
sc := script.NewScriptFromBytes(vout.ScriptPubKey)
// common tx
if !sc.IsContractPubkey() {
outPoint := types.NewOutPoint(txHash, txOutIdx)
utxoWrap, exists := u.utxoMap[*outPoint]
if exists {
return core.ErrAddExistingUtxo
}
utxoWrap = types.NewUtxoWrap(vout.Value, vout.ScriptPubKey, blockHeight)
if IsCoinBase(tx) {
utxoWrap.SetCoinBase()
}
u.utxoMap[*outPoint] = utxoWrap
if !txlogic.HasContractVout(tx) {
u.normalTxUtxoSet[*outPoint] = struct{}{}
}
return nil
}
// smart contract utxo
var (
outPoint *types.OutPoint
utxoWrap *types.UtxoWrap
)
if IsCoinBase(tx) {
return errors.New("Invalid smart contract tx")
}
contractAddr, err := sc.ParseContractAddr()
if err != nil {
return err
}
deploy := contractAddr == nil
if deploy {
// deploy smart contract
from, _ := sc.ParseContractFrom()
nonce, _ := sc.ParseContractNonce()
contractAddr, _ := types.MakeContractAddress(from, nonce)
addressHash := types.NormalizeAddressHash(contractAddr.Hash160())
outPoint = types.NewOutPoint(addressHash, 0)
utxoWrap = types.NewUtxoWrap(0, vout.ScriptPubKey, blockHeight)
} else {
// call smart contract
addressHash := types.NormalizeAddressHash(contractAddr.Hash160())
outPoint = types.NewOutPoint(addressHash, 0)
var exists bool
utxoWrap, exists = u.utxoMap[*outPoint]
if !exists {
return fmt.Errorf("contract utxo[%v] not found in utxoset", outPoint)
}
}
if deploy || vout.Value > 0 {
value := utxoWrap.Value() + vout.Value
logger.Infof("modify contract utxo, outpoint: %+v, value: %d, previous value: %d",
outPoint, value, utxoWrap.Value())
utxoWrap.SetValue(value)
u.utxoMap[*outPoint] = utxoWrap
u.contractUtxos = append(u.contractUtxos, outPoint)
}
return nil
}
// applyTx updates utxos with the passed tx: adds all utxos in outputs and delete all utxos in inputs.
func (u *UtxoSet) applyTx(tx *types.Transaction, blockHeight uint32) error {
// Add new utxos
for txOutIdx := range tx.Vout {
if err := u.applyUtxo(tx, (uint32)(txOutIdx), blockHeight); err != nil {
if err == core.ErrAddExistingUtxo {
// This can occur when a tx spends from another tx in front of it in the same block
continue
}
return err
}
}
// Coinbase transaction doesn't spend any utxo.
if IsCoinBase(tx) {
return nil
}
// Spend the referenced utxos
for _, txIn := range tx.Vin {
u.SpendUtxo(txIn.PrevOutPoint)
if !txlogic.HasContractVout(tx) {
u.normalTxUtxoSet[txIn.PrevOutPoint] = struct{}{}
}
}
return nil
}
func (u *UtxoSet) applyInternalTx(tx *types.Transaction, blockHeight uint32) error {
for txOutIdx := range tx.Vout {
if err := u.applyUtxo(tx, (uint32)(txOutIdx), blockHeight); err != nil {
if err == core.ErrAddExistingUtxo {
continue
}
return err
}
}
return nil
}
// ApplyInternalTxs applies internal txs in block
func (u *UtxoSet) ApplyInternalTxs(block *types.Block) error {
for _, tx := range block.InternalTxs {
if err := u.applyInternalTx(tx, block.Header.Height); err != nil {
return err
}
}
return nil
}
// ApplyBlock updates utxos with all transactions in the passed block
func (u *UtxoSet) ApplyBlock(block *types.Block) error {
txs := block.Txs
for _, tx := range txs {
if err := u.applyTx(tx, block.Header.Height); err != nil {
return err
}
}
logger.Debugf("UTXO: apply block %s with %d transactions", block.BlockHash(), len(block.Txs))
return nil
}
// RevertTx updates utxos with the passed tx: delete all utxos in outputs and add all utxos in inputs.
// It undoes the effect of ApplyTx on utxo set
func (u *UtxoSet) RevertTx(tx *types.Transaction, chain *BlockChain) error {
txHash, _ := tx.TxHash()
// Remove added utxos
for i, o := range tx.Vout {
sc := script.NewScriptFromBytes(o.ScriptPubKey)
if sc.IsContractPubkey() {
continue
}
u.SpendUtxo(*types.NewOutPoint(txHash, uint32(i)))
}
// Coinbase transaction doesn't spend any utxo.
if IsCoinBase(tx) {
return nil
}
// "Unspend" the referenced utxos
for _, txIn := range tx.Vin {
if txIn.PrevOutPoint.IsContractType() {
continue
}
utxoWrap := u.utxoMap[txIn.PrevOutPoint]
if utxoWrap != nil {
utxoWrap.UnSpend()
continue
}
// This can happen when the block the tx is in is being reverted
// The UTXO txIn spends have been deleted from UTXO set, so we load it from tx index
block, prevTx, err := chain.LoadBlockInfoByTxHash(txIn.PrevOutPoint.Hash)
if err != nil {
logger.Errorf("Failed to load block info by txhash. Err: %s", err)
logger.Panicf("Trying to unspend non-existing spent output %v", txIn.PrevOutPoint)
}
// prevTx := block.Txs[txIdx]
prevOut := prevTx.Vout[txIn.PrevOutPoint.Index]
utxoWrap = types.NewUtxoWrap(prevOut.Value, prevOut.ScriptPubKey, block.Header.Height)
if IsCoinBase(prevTx) {
utxoWrap.SetCoinBase()
}
u.utxoMap[txIn.PrevOutPoint] = utxoWrap
}
return nil
}
// RevertBlock undoes utxo changes made with all the transactions in the passed block
// It undoes the effect of ApplyBlock on utxo set
func (u *UtxoSet) RevertBlock(block *types.Block, chain *BlockChain) error {
// Loop backwards through all transactions so everything is unspent in reverse order.
// This is necessary since transactions later in a block can spend from previous ones.
txs := block.Txs
if len(block.InternalTxs) > 0 {
txs = append(txs, block.InternalTxs...)
}
for txIdx := len(txs) - 1; txIdx >= 0; txIdx-- {
tx := txs[txIdx]
if err := u.RevertTx(tx, chain); err != nil {
return err
}
}
return nil
}
var maxUint32VLQSerializeSize = serializeSizeVLQ(1<<32 - 1)
// outpointKeyPool defines a concurrent safe free list of byte slices used to
// provide temporary buffers for outpoint database keys.
var outpointKeyPool = sync.Pool{
New: func() interface{} {
b := make([]byte, crypto.HashSize+maxUint32VLQSerializeSize)
return &b // Pointer to slice to avoid boxing alloc.
},
}
func utxoKey(outpoint types.OutPoint) *[]byte {
key := outpointKeyPool.Get().(*[]byte)
idx := uint64(outpoint.Index)
*key = (*key)[:crypto.HashSize+serializeSizeVLQ(idx)]
copy(*key, outpoint.Hash[:])
putVLQ((*key)[crypto.HashSize:], idx)
return key
}
func recycleOutpointKey(key *[]byte) {
outpointKeyPool.Put(key)
}
func utxoWrapHeaderCode(utxoWrap *types.UtxoWrap) (uint64, error) {
if utxoWrap.IsSpent() {
return 0, errors.New("attempt to serialize spent utxo header")
}
// As described in the serialization format comments, the header code
// encodes the height shifted over one bit and the coinbase flag in the
// lowest bit.
headerCode := uint64(utxoWrap.Height()) << 1
if utxoWrap.IsCoinBase() {
headerCode |= 0x01
}
return headerCode, nil
}
// SerializeUtxoWrap returns the utxoWrap serialized to a format that is suitable
// for long-term storage.
func SerializeUtxoWrap(utxoWrap *types.UtxoWrap) ([]byte, error) {
// Spent outputs have no serialization.
if utxoWrap.IsSpent() {
return nil, nil
}
// Encode the header code.
headerCode, err := utxoWrapHeaderCode(utxoWrap)
if err != nil {
return nil, err
}
size := serializeSizeVLQ(headerCode) +
compressedTxOutSize(utxoWrap.Value(), utxoWrap.Script())
serialized := make([]byte, size)
offset := putVLQ(serialized, headerCode)
offset += compressedTxOut(serialized[offset:], uint64(utxoWrap.Value()),
utxoWrap.Script())
return serialized, nil
}
// DeserializeUtxoWrap returns UtxoWrap form serialized bytes.
func DeserializeUtxoWrap(serialized []byte) (*types.UtxoWrap, error) {
// Deserialize the header code.
code, offset := deserializeVLQ(serialized)
if offset >= len(serialized) {
return nil, errors.New("unexpected end of data after header")
}
isCoinBase := code&0x01 != 0
blockHeight := uint32(code >> 1)
// Decode the compressed unspent transaction output.
value, pkScript, _, err := decodeCompressedTxOut(serialized[offset:])
if err != nil {
return nil, fmt.Errorf(fmt.Sprintf("unable to decode "+
"utxo: %v", err))
}
utxoWrap := types.NewUtxoWrap(value, pkScript, blockHeight)
if isCoinBase {
utxoWrap.SetCoinBase()
}
return utxoWrap, nil
}
// WriteUtxoSetToDB store utxo set to database.
func (u *UtxoSet) WriteUtxoSetToDB(db storage.Table) error {
for outpoint, utxoWrap := range u.utxoMap {
if utxoWrap == nil || !utxoWrap.IsModified() {
continue
}
utxoKey := utxoKey(outpoint)
var addrUtxoKey []byte
if len(utxoWrap.Script()) == 0 { // for the utxo deleted from db later
if outpoint.IsContractType() {
addrHash := types.BytesToAddressHash(outpoint.Hash[:])
addr, _ := types.NewContractAddressFromHash(addrHash[:])
addrUtxoKey = AddrUtxoKey(addr.String(), outpoint)
}
} else {
sc := script.NewScriptFromBytes(utxoWrap.Script())
addr, err := sc.ExtractAddress()
if err != nil {
logger.Warnf("Failed to extract address. utxoWrap: %+v, sc disasm: %s, hex: %x, Err: %s",
utxoWrap, sc.Disasm(), utxoWrap.Script(), err)
return err
}
if sc.IsTokenTransfer() || sc.IsTokenIssue() {
var tokenID types.OutPoint
if sc.IsTokenTransfer() {
v, err := sc.GetTransferParams()
if err != nil {
logger.Warnf("Failed to get transfer param when write utxo to db. Err: %v", err)
}
tokenID = v.OutPoint
} else {
tokenID = outpoint
}
addrUtxoKey = AddrTokenUtxoKey(addr.String(), types.TokenID(tokenID), outpoint)
} else if sc.IsContractPubkey() {
addrHash := types.BytesToAddressHash(outpoint.Hash[:])
addr, _ := types.NewContractAddressFromHash(addrHash[:])
addrUtxoKey = AddrUtxoKey(addr.String(), outpoint)
} else {
addrUtxoKey = AddrUtxoKey(addr.String(), outpoint)
}
}
// Remove the utxo entry if it is spent.
if utxoWrap.IsSpent() {
db.Del(*utxoKey)
db.Del(addrUtxoKey)
// recycleOutpointKey(utxoKey)
continue
} else if utxoWrap.IsModified() {
// Serialize and store the utxo entry.
serialized, err := SerializeUtxoWrap(utxoWrap)
if err != nil {
return err
}
db.Put(*utxoKey, serialized)
db.Put(addrUtxoKey, serialized)
}
}
return nil
}
// LoadTxUtxos loads the unspent transaction outputs related to tx
func (u *UtxoSet) LoadTxUtxos(tx *types.Transaction, db storage.Table) error {
if IsCoinBase(tx) {
return nil
}
outPointsToFetch := make(map[types.OutPoint]struct{})
for _, txIn := range tx.Vin {
outPointsToFetch[txIn.PrevOutPoint] = struct{}{}
}
return u.fetchUtxosFromOutPointSet(outPointsToFetch, db)
}
// LoadBlockUtxos loads UTXOs txs in the block spend
func (u *UtxoSet) LoadBlockUtxos(block *types.Block, needContract bool, db storage.Table) error {
outPointsToFetch := make(map[types.OutPoint]struct{})
txs := map[crypto.HashType]int{}
for index, tx := range block.Txs {
hash, _ := tx.TxHash()
txs[*hash] = index
}
for i, tx := range block.Txs[1:] {
for _, txIn := range tx.Vin {
if !needContract && txIn.PrevOutPoint.IsContractType() {
continue
}
preHash := &txIn.PrevOutPoint.Hash
// i points to txs[i + 1], which should be after txs[index]
// Thus (i + 1) > index, equavalently, i >= index
if index, ok := txs[*preHash]; ok && i >= index {
originTx := block.Txs[index]
if err := u.AddUtxo(originTx, txIn.PrevOutPoint.Index, block.Header.Height); err != nil {
logger.Error(err)
}
continue
}
if _, ok := u.utxoMap[txIn.PrevOutPoint]; ok {
continue
}
outPointsToFetch[txIn.PrevOutPoint] = struct{}{}
}
if !needContract {
continue
}
// add utxo for contract vout script pubkey
for _, txOut := range tx.Vout {
sc := script.NewScriptFromBytes(txOut.ScriptPubKey)
if sc.IsContractPubkey() {
contractAddr, err := sc.ParseContractAddr()
if err != nil {
logger.Warn(err)
return err
}
if contractAddr == nil || reflect.ValueOf(contractAddr).IsNil() {
continue
}
hash := types.NormalizeAddressHash(contractAddr.Hash160())
outPoint := types.NewOutPoint(hash, 0)
outPointsToFetch[*outPoint] = struct{}{}
}
}
}
if len(outPointsToFetch) > 0 {
if err := u.fetchUtxosFromOutPointSet(outPointsToFetch, db); err != nil {
return err
}
}
return nil
}
// LoadBlockAllUtxos loads all UTXOs txs in the block
func (u *UtxoSet) LoadBlockAllUtxos(block *types.Block, needContract bool, db storage.Table) error {
// for vin
u.LoadBlockUtxos(block, needContract, db)
// for vout
outPointsToFetch := make(map[types.OutPoint]struct{})
txs := block.Txs
if len(block.InternalTxs) > 0 {
txs = append(txs, block.InternalTxs...)
}
for _, tx := range txs {
hash, _ := tx.TxHash()
outPoint := types.OutPoint{Hash: *hash}
for idx, out := range tx.Vout {
sc := script.NewScriptFromBytes(out.ScriptPubKey)
if !needContract && sc.IsContractPubkey() {
continue
}
outPoint.Index = uint32(idx)
outPointsToFetch[outPoint] = struct{}{}
}
}
if len(outPointsToFetch) > 0 {
if err := u.fetchUtxosFromOutPointSet(outPointsToFetch, db); err != nil {
return err
}
}
return nil
}
func (u *UtxoSet) fetchUtxosFromOutPointSet(outPoints map[types.OutPoint]struct{}, db storage.Table) error {
for outPoint := range outPoints {
entry, err := fetchUtxoWrapFromDB(db, &outPoint)
if err != nil {
return err
}
if entry != nil {
u.utxoMap[outPoint] = entry
}
}
return nil
}
func fetchUtxoWrapFromDB(reader storage.Reader, outpoint *types.OutPoint) (*types.UtxoWrap, error) {
utxoKey := utxoKey(*outpoint)
serializedUtxoWrap, err := reader.Get(*utxoKey)
recycleOutpointKey(utxoKey)
if err != nil {
return nil, err
}
if serializedUtxoWrap == nil {
return nil, nil
}
var utxoWrap *types.UtxoWrap
if utxoWrap, err = DeserializeUtxoWrap(serializedUtxoWrap); err != nil {
return nil, err
}
return utxoWrap, nil
}
func (u *UtxoSet) calcNormalTxBalanceChanges(block *types.Block) (add, sub BalanceChangeMap) {
add = make(BalanceChangeMap)
sub = make(BalanceChangeMap)
for _, v := range block.Txs {
if !txlogic.HasContractVout(v) {
for _, vout := range v.Vout {
sc := script.NewScriptFromBytes(vout.ScriptPubKey)
// calc balance for account state, here only EOA (external owned account)
// have balance state
if !sc.IsPayToPubKeyHash() {
continue
}
address, _ := sc.ExtractAddress()
addr := address.Hash160()
add[*addr] += vout.Value
//logger.Warnf("add addr: %s, value: %d", addr, vout.Value)
}
}
}
for o, w := range u.utxoMap {
_, exists := u.normalTxUtxoSet[o]
if !exists {
continue
}
sc := script.NewScriptFromBytes(w.Script())
// calc balance for account state, here only EOA (external owned account)
// have balance state
if !sc.IsPayToPubKeyHash() {
continue
}
address, _ := sc.ExtractAddress()
addr := address.Hash160()
if w.IsSpent() {
sub[*addr] += w.Value()
}
}
return
}
// MakeRollbackContractUtxos makes finally contract utxos from block
func MakeRollbackContractUtxos(
block *types.Block, stateDB *state.StateDB, db storage.Table,
) (types.UtxoMap, error) {
// prevStateDB
prevBlock, err := LoadBlockByHash(block.Header.PrevBlockHash, db)
if err != nil {
return nil, err
}
prevHeader := prevBlock.Header
prevStateDB, err := state.New(&prevHeader.RootHash, &prevHeader.UtxoRoot, db)
if err != nil {
return nil, err
}
// balances added and subtracted
bAdd, bSub, err := calcContractAddrBalanceChanges(block)
if err != nil {
logger.Errorf("calc contract addr balance changes error: %s", err)
return nil, err
}
balances := make(map[types.AddressHash]uint64, len(bAdd)+len(bSub))
um := make(types.UtxoMap)
height := block.Header.Height
for a, v := range bAdd {
ah := types.NormalizeAddressHash(&a)
op := types.NewOutPoint(ah, 0)
if _, ok := balances[a]; !ok {
balances[a] = stateDB.GetBalance(a).Uint64()
sc := script.MakeContractUtxoScriptPubkey(&types.ZeroAddressHash, &a, prevStateDB.GetNonce(a), types.VMVersion)
um[*op] = types.NewUtxoWrap(balances[a], []byte(*sc), height)
}
utxo := um[*op]
utxo.SetValue(utxo.Value() - v)
}
for a, v := range bSub {
ah := types.NormalizeAddressHash(&a)
op := types.NewOutPoint(ah, 0)
if _, ok := balances[a]; !ok {
balances[a] = stateDB.GetBalance(a).Uint64()
sc := script.MakeContractUtxoScriptPubkey(&types.ZeroAddressHash, &a, prevStateDB.GetNonce(a), types.VMVersion)
um[*op] = types.NewUtxoWrap(balances[a], []byte(*sc), height)
}
utxo := um[*op]
utxo.SetValue(utxo.Value() + v)
}
//
for op, u := range um {
ah := new(types.AddressHash)
ah.SetBytes(op.Hash[:])
b := prevStateDB.GetBalance(*ah)
if b.Uint64() != u.Value() {
addr, _ := types.NewContractAddressFromHash(ah[:])
return nil, fmt.Errorf("block %s: contract addr %s rollback to incorrect "+
"balance: %d, need: %d", block.BlockHash(), addr, u.Value(), b)
}
utxoBytes, err := prevStateDB.GetUtxo(*ah)
if err != nil {
return nil, err
}
if utxoBytes == nil {
u.Spend()
continue
}
utxoWrap, err := DeserializeUtxoWrap(utxoBytes)
if err != nil {
return nil, err
}
um[op] = utxoWrap
}
return um, nil
}