/
blockscaner.go
1564 lines (1263 loc) · 39.4 KB
/
blockscaner.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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2018 The openwallet Authors
* This file is part of the openwallet library.
*
* The openwallet library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The openwallet library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package handshake
import (
"errors"
"fmt"
"net/url"
"strings"
"sync"
"time"
"github.com/blocktree/openwallet/v2/common"
"github.com/blocktree/openwallet/v2/openwallet"
"github.com/graarh/golang-socketio"
"github.com/graarh/golang-socketio/transport"
"github.com/shopspring/decimal"
)
const (
//blockchainBucket = "blockchain" //区块链数据集合
//periodOfTask = 5 * time.Second //定时任务执行隔间
maxExtractingSize = 6 //并发的扫描线程数
//RPCServerCore = 0 //RPC服务,handshake核心钱包
//RPCServerExplorer = 1 //RPC服务,insight-API
)
//HNSBlockScanner handshake的区块链扫描器
type HNSBlockScanner struct {
*openwallet.BlockScannerBase
CurrentBlockHeight uint64 //当前区块高度
extractingCH chan struct{} //扫描工作令牌
wm *WalletManager //钱包管理者
IsScanMemPool bool //是否扫描交易池
RescanLastBlockCount uint64 //重扫上N个区块数量
socketIO *gosocketio.Client //socketIO客户端
setupSocketIOOnce sync.Once
stopSocketIO chan struct{}
//用于实现浏览器
IsSkipFailedBlock bool //是否跳过失败区块
HNSBlockObservers map[HNSBlockScanNotificationObject]bool //观察者
}
//ExtractResult 扫描完成的提取结果
type ExtractResult struct {
extractData map[string]*openwallet.TxExtractData
//extractOmniData map[string]*openwallet.TxExtractData //代币交易
TxID string
BlockHeight uint64
Success bool
//IsOmniTransfer bool
}
//SaveResult 保存结果
type SaveResult struct {
TxID string
BlockHeight uint64
Success bool
}
//NewHNSBlockScanner 创建区块链扫描器
func NewHNSBlockScanner(wm *WalletManager) *HNSBlockScanner {
bs := HNSBlockScanner{
BlockScannerBase: openwallet.NewBlockScannerBase(),
}
bs.extractingCH = make(chan struct{}, maxExtractingSize)
bs.wm = wm
bs.IsScanMemPool = true
bs.RescanLastBlockCount = 0
bs.stopSocketIO = make(chan struct{})
bs.HNSBlockObservers = make(map[HNSBlockScanNotificationObject]bool)
//bs.RPCServer = RPCServerCore
//设置扫描任务
bs.SetTask(bs.ScanBlockTask)
return &bs
}
//SetRescanBlockHeight 重置区块链扫描高度
func (bs *HNSBlockScanner) SetRescanBlockHeight(height uint64) error {
height = height - 1
if height < 0 {
return errors.New("block height to rescan must greater than 0.")
}
hash, err := bs.wm.GetBlockHash(height)
if err != nil {
return err
}
bs.SaveLocalNewBlock(height, hash)
return nil
}
//ScanBlockTask 扫描任务
func (bs *HNSBlockScanner) ScanBlockTask() {
//获取本地区块高度
blockHeader, err := bs.GetScannedBlockHeader()
if err != nil {
bs.wm.Log.Std.Info("block scanner can not get new block height; unexpected error: %v", err)
return
}
currentHeight := blockHeader.Height
currentHash := blockHeader.Hash
for {
if !bs.Scanning {
//区块扫描器已暂停,马上结束本次任务
return
}
//获取最大高度
maxHeight, err := bs.wm.GetBlockHeight()
if err != nil {
//下一个高度找不到会报异常
bs.wm.Log.Std.Info("block scanner can not get rpc-server block height; unexpected error: %v", err)
break
}
//是否已到最新高度
if currentHeight >= maxHeight {
bs.wm.Log.Std.Info("block scanner has scanned full chain data. Current height: %d", maxHeight)
break
}
//继续扫描下一个区块
currentHeight = currentHeight + 1
bs.wm.Log.Std.Info("block scanner scanning height: %d ...", currentHeight)
hash, err := bs.wm.GetBlockHash(currentHeight)
if err != nil {
//下一个高度找不到会报异常
bs.wm.Log.Std.Info("block scanner can not get new block hash; unexpected error: %v", err)
break
}
//if bs.wm.Config.OmniSupport {
// //判断omni的区块高度是否一致
// omniBlockHash, err := bs.wm.GetOmniBlockHash(currentHeight)
// if err != nil {
// bs.wm.Log.Std.Error("omni block is not synced to the same height of mainnet")
// return
// }
//
// //判断omni的hash是否与hc节点的hash一致
// if omniBlockHash != hash {
// bs.wm.Log.Std.Error("omni block is not synced to the same hash of mainnet")
// return
// }
//}
block, err := bs.wm.GetBlock(hash)
if err != nil {
bs.wm.Log.Std.Info("block scanner can not get new block data; unexpected error: %v", err)
//记录未扫区块
unscanRecord := openwallet.NewUnscanRecord(currentHeight, "", err.Error(), bs.wm.Symbol())
bs.SaveUnscanRecord(unscanRecord)
bs.wm.Log.Std.Info("block height: %d extract failed.", currentHeight)
continue
}
isFork := false
//判断hash是否上一区块的hash
if currentHash != block.Previousblockhash {
bs.wm.Log.Std.Info("block has been fork on height: %d.", currentHeight)
bs.wm.Log.Std.Info("block height: %d local hash = %s ", currentHeight-1, currentHash)
bs.wm.Log.Std.Info("block height: %d mainnet hash = %s ", currentHeight-1, block.Previousblockhash)
bs.wm.Log.Std.Info("delete recharge records on block height: %d.", currentHeight-1)
//查询本地分叉的区块
forkBlock, _ := bs.GetLocalBlock(currentHeight - 1)
//删除上一区块链的所有充值记录
//bs.DeleteRechargesByHeight(currentHeight - 1)
//删除上一区块链的未扫记录
bs.DeleteUnscanRecord(currentHeight - 1)
currentHeight = currentHeight - 2 //倒退2个区块重新扫描
if currentHeight <= 0 {
currentHeight = 1
}
localBlock, err := bs.GetLocalBlock(currentHeight)
if err != nil {
bs.wm.Log.Std.Error("block scanner can not get local block; unexpected error: %v", err)
//查找core钱包的RPC
bs.wm.Log.Info("block scanner prev block height:", currentHeight)
prevHash, err := bs.wm.GetBlockHash(currentHeight)
if err != nil {
bs.wm.Log.Std.Error("block scanner can not get prev block; unexpected error: %v", err)
break
}
localBlock, err = bs.wm.GetBlock(prevHash)
if err != nil {
bs.wm.Log.Std.Error("block scanner can not get prev block; unexpected error: %v", err)
break
}
}
//重置当前区块的hash
currentHash = localBlock.Hash
bs.wm.Log.Std.Info("rescan block on height: %d, hash: %s .", currentHeight, currentHash)
//重新记录一个新扫描起点
bs.SaveLocalNewBlock(localBlock.Height, localBlock.Hash)
isFork = true
if forkBlock != nil {
//通知分叉区块给观测者,异步处理
bs.newBlockNotify(forkBlock, isFork)
}
} else {
err = bs.BatchExtractTransaction(block.Height, block.Hash, block.tx)
if err != nil {
bs.wm.Log.Std.Info("block scanner can not extractRechargeRecords; unexpected error: %v", err)
}
//重置当前区块的hash
currentHash = hash
//保存本地新高度
bs.SaveLocalNewBlock(currentHeight, currentHash)
bs.SaveLocalBlock(block)
isFork = false
//通知新区块给观测者,异步处理
bs.newBlockNotify(block, isFork)
}
}
//重扫前N个块,为保证记录找到
for i := currentHeight - bs.RescanLastBlockCount; i < currentHeight; i++ {
bs.scanBlock(i)
}
if bs.IsScanMemPool {
//扫描交易内存池
bs.ScanTxMemPool()
}
//重扫失败区块
bs.RescanFailedRecord()
}
//ScanBlock 扫描指定高度区块
func (bs *HNSBlockScanner) ScanBlock(height uint64) error {
block, err := bs.scanBlock(height)
if err != nil {
return err
}
//通知新区块给观测者,异步处理
bs.newBlockNotify(block, false)
return nil
}
func (bs *HNSBlockScanner) scanBlock(height uint64) (*Block, error) {
hash, err := bs.wm.GetBlockHash(height)
if err != nil {
//下一个高度找不到会报异常
bs.wm.Log.Std.Info("block scanner can not get new block hash; unexpected error: %v", err)
return nil, err
}
block, err := bs.wm.GetBlock(hash)
if err != nil {
bs.wm.Log.Std.Info("block scanner can not get new block data; unexpected error: %v", err)
//记录未扫区块
unscanRecord := openwallet.NewUnscanRecord(height, "", err.Error(), bs.wm.Symbol())
bs.SaveUnscanRecord(unscanRecord)
bs.wm.Log.Std.Info("block height: %d extract failed.", height)
return nil, err
}
bs.wm.Log.Std.Info("block scanner scanning height: %d ...", block.Height)
err = bs.BatchExtractTransaction(block.Height, block.Hash, block.tx)
if err != nil {
bs.wm.Log.Std.Info("block scanner can not extractRechargeRecords; unexpected error: %v", err)
}
//保存区块
//bs.wm.SaveLocalBlock(block)
return block, nil
}
//ScanTxMemPool 扫描交易内存池
func (bs *HNSBlockScanner) ScanTxMemPool() {
bs.wm.Log.Std.Info("block scanner scanning mempool ...")
//提取未确认的交易单
txIDsInMemPool, err := bs.wm.GetTxIDsInMemPool()
if err != nil {
bs.wm.Log.Std.Info("block scanner can not get mempool data; unexpected error: %v", err)
return
}
if txIDsInMemPool == nil || len(txIDsInMemPool) == 0 {
return
}
err = bs.BatchExtractTransaction(0, "", txIDsInMemPool)
if err != nil {
bs.wm.Log.Std.Info("block scanner can not extractRechargeRecords; unexpected error: %v", err)
}
}
//rescanFailedRecord 重扫失败记录
func (bs *HNSBlockScanner) RescanFailedRecord() {
var (
blockMap = make(map[uint64][]string)
)
list, err := bs.GetUnscanRecords()
if err != nil {
bs.wm.Log.Std.Info("block scanner can not get rescan data; unexpected error: %v", err)
}
//组合成批处理
for _, r := range list {
if _, exist := blockMap[r.BlockHeight]; !exist {
blockMap[r.BlockHeight] = make([]string, 0)
}
if len(r.TxID) > 0 {
arr := blockMap[r.BlockHeight]
arr = append(arr, r.TxID)
blockMap[r.BlockHeight] = arr
}
}
for height, txs := range blockMap {
if height == 0 {
continue
}
var hash string
bs.wm.Log.Std.Info("block scanner rescanning height: %d ...", height)
if len(txs) == 0 {
hash, err := bs.wm.GetBlockHash(height)
if err != nil {
//下一个高度找不到会报异常
bs.wm.Log.Std.Info("block scanner can not get new block hash; unexpected error: %v", err)
continue
}
block, err := bs.wm.GetBlock(hash)
if err != nil {
bs.wm.Log.Std.Info("block scanner can not get new block data; unexpected error: %v", err)
continue
}
txs = block.tx
}
err = bs.BatchExtractTransaction(height, hash, txs)
if err != nil {
bs.wm.Log.Std.Info("block scanner can not extractRechargeRecords; unexpected error: %v", err)
continue
}
//删除未扫记录
bs.DeleteUnscanRecord(height)
}
//删除未没有找到交易记录的重扫记录
bs.DeleteUnscanRecordNotFindTX()
}
//newBlockNotify 获得新区块后,通知给观测者
func (bs *HNSBlockScanner) newBlockNotify(block *Block, isFork bool) {
header := block.BlockHeader(bs.wm.Symbol())
header.Fork = isFork
bs.NewBlockNotify(header)
}
//BatchExtractTransaction 批量提取交易单
//handshake 1M的区块链可以容纳3000笔交易,批量多线程处理,速度更快
func (bs *HNSBlockScanner) BatchExtractTransaction(blockHeight uint64, blockHash string, txs []string) error {
var (
quit = make(chan struct{})
done = 0 //完成标记
failed = 0
shouldDone = len(txs) //需要完成的总数
)
if len(txs) == 0 {
return errors.New("BatchExtractTransaction block is nil.")
}
//生产通道
producer := make(chan ExtractResult)
defer close(producer)
//消费通道
worker := make(chan ExtractResult)
defer close(worker)
//保存工作
saveWork := func(height uint64, result chan ExtractResult) {
//回收创建的地址
for gets := range result {
if gets.Success {
notifyErr := bs.newExtractDataNotify(height, gets.extractData)
//saveErr := bs.SaveRechargeToWalletDB(height, gets.Recharges)
if notifyErr != nil {
failed++ //标记保存失败数
bs.wm.Log.Std.Info("newExtractDataNotify unexpected error: %v", notifyErr)
}
//notifyErr = nil
//notifyErr = bs.newExtractDataNotify(height, gets.extractOmniData)
//if notifyErr != nil {
// failed++ //标记保存失败数
// bs.wm.Log.Std.Info("newExtractDataNotify unexpected error: %v", notifyErr)
//}
} else {
//记录未扫区块
unscanRecord := openwallet.NewUnscanRecord(height, "", "", bs.wm.Symbol())
bs.SaveUnscanRecord(unscanRecord)
bs.wm.Log.Std.Info("block height: %d extract failed.", height)
failed++ //标记保存失败数
}
//累计完成的线程数
done++
if done == shouldDone {
//bs.wm.Log.Std.Info("done = %d, shouldDone = %d ", done, len(txs))
close(quit) //关闭通道,等于给通道传入nil
}
}
}
//提取工作
extractWork := func(eblockHeight uint64, eBlockHash string, mTxs []string, eProducer chan ExtractResult) {
for _, txid := range mTxs {
bs.extractingCH <- struct{}{}
//shouldDone++
go func(mBlockHeight uint64, mTxid string, end chan struct{}, mProducer chan<- ExtractResult) {
//导出提出的交易
mProducer <- bs.ExtractTransaction(mBlockHeight, eBlockHash, mTxid, bs.ScanTargetFunc)
//释放
<-end
}(eblockHeight, txid, bs.extractingCH, eProducer)
}
}
/* 开启导出的线程 */
//独立线程运行消费
go saveWork(blockHeight, worker)
//独立线程运行生产
go extractWork(blockHeight, blockHash, txs, producer)
//以下使用生产消费模式
bs.extractRuntime(producer, worker, quit)
if failed > 0 {
return fmt.Errorf("block scanner saveWork failed")
} else {
return nil
}
//return nil
}
//extractRuntime 提取运行时
func (bs *HNSBlockScanner) extractRuntime(producer chan ExtractResult, worker chan ExtractResult, quit chan struct{}) {
var (
values = make([]ExtractResult, 0)
)
for {
var activeWorker chan<- ExtractResult
var activeValue ExtractResult
//当数据队列有数据时,释放顶部,传输给消费者
if len(values) > 0 {
activeWorker = worker
activeValue = values[0]
}
select {
//生成者不断生成数据,插入到数据队列尾部
case pa := <-producer:
values = append(values, pa)
case <-quit:
//退出
//bs.wm.Log.Std.Info("block scanner have been scanned!")
return
case activeWorker <- activeValue:
//wm.Log.Std.Info("Get %d", len(activeValue))
values = values[1:]
}
}
}
//ExtractTransaction 提取交易单
func (bs *HNSBlockScanner) ExtractTransaction(blockHeight uint64, blockHash string, txid string, scanAddressFunc openwallet.BlockScanTargetFunc) ExtractResult {
var (
result = ExtractResult{
BlockHeight: blockHeight,
TxID: txid,
extractData: make(map[string]*openwallet.TxExtractData),
// extractOmniData: make(map[string]*openwallet.TxExtractData),
}
)
//bs.wm.Log.Std.Debug("block scanner scanning tx: %s ...", txid)
//获取handshake的交易单
trx, err := bs.wm.GetTransaction(txid)
if err != nil {
bs.wm.Log.Std.Info("block scanner can not extract transaction data; unexpected error: %v", err)
result.Success = false
return result
}
//优先使用传入的高度
if blockHeight > 0 && trx.BlockHeight == 0 {
trx.BlockHeight = blockHeight
trx.BlockHash = blockHash
}
bs.extractTransaction(trx, &result, bs.ScanTargetFuncV2)
////bs.wm.Log.Debug("start extractTransaction")
//bs.extractTransaction(trx, &result, scanAddressFunc)
////bs.wm.Log.Debug("end extractTransaction")
//
//if bs.wm.Config.OmniSupport {
// //获取omni的交易单
// omniTrx, err := bs.wm.GetOmniTransaction(txid)
// if err != nil {
// //bs.wm.Log.Std.Info("block scanner can not extract omni transaction data; unexpected error: %v", err)
// result.Success = true
// return result
// }
//
// bs.extractOmniTransaction(omniTrx, &result, scanAddressFunc)
//}
return result
}
//ExtractTransactionData 提取交易单
func (bs *HNSBlockScanner) extractTransaction(trx *Transaction, result *ExtractResult, scanAddressFunc openwallet.BlockScanTargetFuncV2) {
var (
success = true
txType = uint64(0)
)
if trx == nil {
//记录哪个区块哪个交易单没有完成扫描
success = false
} else {
vin := trx.Vins
blocktime := trx.Blocktime
//检查交易单输入信息是否完整,不完整查上一笔交易单的输出填充数据
for _, input := range vin {
if len(input.Coinbase) > 0 {
//coinbase skip
success = true
break
}
//如果input中没有地址,需要查上一笔交易的output提取
if len(input.Addr) == 0 {
intxid := input.TxID
vout := input.Vout
preTx, err := bs.wm.GetTransaction(intxid)
if err != nil {
success = false
break
} else {
preVouts := preTx.Vouts
if len(preVouts) > int(vout) {
preOut := preVouts[vout]
input.Addr = preOut.Addr
input.Value = preOut.Value
//vinout = append(vinout, output[vout])
success = true
//bs.wm.Log.Debug("GetTxOut:", output[vout])
}
}
}
}
if success {
//提取出账部分记录
from, totalSpent := bs.extractTxInput(trx, result, scanAddressFunc)
//bs.wm.Log.Debug("from:", from, "totalSpent:", totalSpent)
//提取入账部分记录
to, totalReceived := bs.extractTxOutput(trx, result, scanAddressFunc)
//bs.wm.Log.Debug("to:", to, "totalReceived:", totalReceived)
for _, extractData := range result.extractData {
tx := &openwallet.Transaction{
From: from,
To: to,
Fees: totalSpent.Sub(totalReceived).StringFixed(bs.wm.Decimal()),
Coin: openwallet.Coin{
Symbol: bs.wm.Symbol(),
IsContract: false,
},
BlockHash: trx.BlockHash,
BlockHeight: trx.BlockHeight,
TxID: trx.TxID,
Decimal: bs.wm.Decimal(),
ConfirmTime: blocktime,
Status: openwallet.TxStatusSuccess,
TxType: txType,
}
wxID := openwallet.GenTransactionWxID(tx)
tx.WxID = wxID
extractData.Transaction = tx
//bs.wm.Log.Debug("Transaction:", extractData.Transaction)
}
}
success = true
}
result.Success = success
}
//ExtractTxInput 提取交易单输入部分
func (bs *HNSBlockScanner) extractTxInput(trx *Transaction, result *ExtractResult, scanAddressFunc openwallet.BlockScanTargetFuncV2) ([]string, decimal.Decimal) {
//vin := trx.Get("vin")
var (
from = make([]string, 0)
totalAmount = decimal.Zero
txType = uint64(0)
)
//if result.IsOmniTransfer {
// txType = 1
//}
createAt := time.Now().Unix()
for i, output := range trx.Vins {
//in := vin[i]
txid := output.TxID
vout := output.Vout
//
//output, err := bs.wm.GetTxOut(txid, vout)
//if err != nil {
// return err
//}
amount := output.Value
addr := output.Addr
targetResult := scanAddressFunc(openwallet.ScanTargetParam{
ScanTarget: addr,
Symbol: bs.wm.Symbol(),
ScanTargetType: openwallet.ScanTargetTypeAccountAddress,
})
if targetResult.Exist {
input := openwallet.TxInput{}
input.SourceTxID = txid
input.SourceIndex = vout
input.TxID = result.TxID
input.Address = addr
//transaction.AccountID = a.AccountID
input.Amount = amount
input.Coin = openwallet.Coin{
Symbol: bs.wm.Symbol(),
IsContract: false,
}
input.Index = output.N
input.Sid = openwallet.GenTxInputSID(txid, bs.wm.Symbol(), "", uint64(i))
//input.Sid = base64.StdEncoding.EncodeToString(crypto.SHA1([]byte(fmt.Sprintf("input_%s_%d_%s", result.TxID, i, addr))))
input.CreateAt = createAt
//在哪个区块高度时消费
input.BlockHeight = trx.BlockHeight
input.BlockHash = trx.BlockHash
input.TxType = txType
//transactions = append(transactions, &transaction)
ed := result.extractData[targetResult.SourceKey]
if ed == nil {
ed = openwallet.NewBlockExtractData()
result.extractData[targetResult.SourceKey] = ed
}
ed.TxInputs = append(ed.TxInputs, &input)
}
from = append(from, addr+":"+amount)
dAmount, _ := decimal.NewFromString(amount)
totalAmount = totalAmount.Add(dAmount)
}
return from, totalAmount
}
//ExtractTxInput 提取交易单输入部分
func (bs *HNSBlockScanner) extractTxOutput(trx *Transaction, result *ExtractResult, scanAddressFunc openwallet.BlockScanTargetFuncV2) ([]string, decimal.Decimal) {
var (
to = make([]string, 0)
totalAmount = decimal.Zero
txType = uint64(0)
)
//if result.IsOmniTransfer {
// txType = 1
//}
confirmations := trx.Confirmations
vout := trx.Vouts
txid := trx.TxID
//bs.wm.Log.Debug("vout:", vout.Array())
createAt := time.Now().Unix()
for _, output := range vout {
//not payment
if !(output.Type == "0" && output.Action == "NONE") {
continue
}
amount := output.Value
n := output.N
addr := output.Addr
targetResult := scanAddressFunc(openwallet.ScanTargetParam{
ScanTarget: addr,
Symbol: bs.wm.Symbol(),
ScanTargetType: openwallet.ScanTargetTypeAccountAddress,
})
if targetResult.Exist {
//a := wallet.GetAddress(addr)
//if a == nil {
// continue
//}
outPut := openwallet.TxOutPut{}
outPut.TxID = txid
outPut.Address = addr
//transaction.AccountID = a.AccountID
outPut.Amount = amount
outPut.Coin = openwallet.Coin{
Symbol: bs.wm.Symbol(),
IsContract: false,
}
outPut.Index = n
outPut.Sid = openwallet.GenTxOutPutSID(txid, bs.wm.Symbol(), "", n)
//outPut.Sid = base64.StdEncoding.EncodeToString(crypto.SHA1([]byte(fmt.Sprintf("output_%s_%d_%s", txid, n, addr))))
//保存utxo到扩展字段
outPut.SetExtParam("scriptPubKey", output.ScriptPubKey)
outPut.CreateAt = createAt
outPut.BlockHeight = trx.BlockHeight
outPut.BlockHash = trx.BlockHash
outPut.Confirm = int64(confirmations)
outPut.TxType = txType
//transactions = append(transactions, &transaction)
ed := result.extractData[targetResult.SourceKey]
if ed == nil {
ed = openwallet.NewBlockExtractData()
result.extractData[targetResult.SourceKey] = ed
}
ed.TxOutputs = append(ed.TxOutputs, &outPut)
}
to = append(to, addr+":"+amount)
dAmount, _ := decimal.NewFromString(amount)
totalAmount = totalAmount.Add(dAmount)
}
return to, totalAmount
}
//newExtractDataNotify 发送通知
func (bs *HNSBlockScanner) newExtractDataNotify(height uint64, extractData map[string]*openwallet.TxExtractData) error {
for o, _ := range bs.Observers {
for key, data := range extractData {
err := o.BlockExtractDataNotify(key, data)
if err != nil {
bs.wm.Log.Error("BlockExtractDataNotify unexpected error:", err)
//记录未扫区块
unscanRecord := openwallet.NewUnscanRecord(height, "", "ExtractData Notify failed.", bs.wm.Symbol())
err = bs.SaveUnscanRecord(unscanRecord)
if err != nil {
bs.wm.Log.Std.Error("block height: %d, save unscan record failed. unexpected error: %v", height, err.Error())
}
}
}
}
return nil
}
//DeleteUnscanRecordNotFindTX 删除未没有找到交易记录的重扫记录
func (bs *HNSBlockScanner) DeleteUnscanRecordNotFindTX() error {
//删除找不到交易单
reason := "[-5]No information available about transaction"
if bs.BlockchainDAI == nil {
return fmt.Errorf("Blockchain DAI is not setup ")
}
list, err := bs.BlockchainDAI.GetUnscanRecords(bs.wm.Symbol())
if err != nil {
return err
}
for _, r := range list {
if strings.HasPrefix(r.Reason, reason) {
bs.BlockchainDAI.DeleteUnscanRecordByID(r.ID, bs.wm.Symbol())
}
}
return nil
}
//SaveRechargeToWalletDB 保存交易单内的充值记录到钱包数据库
//func (bs *HNSBlockScanner) SaveRechargeToWalletDB(height uint64, list []*openwallet.Recharge) error {
//
// for _, r := range list {
//
// //accountID := "W4ruoAyS5HdBMrEeeHQTBxo4XtaAixheXQ"
// wallet, ok := bs.GetWalletByAddress(r.Address)
// if ok {
//
// //a := wallet.GetAddress(r.Address)
// //if a == nil {
// // continue
// //}
// //
// //r.AccountID = a.AccountID
//
// err := wallet.SaveUnreceivedRecharge(r)
// //如果blockHash没有值,添加到重扫,避免遗留
// if err != nil || len(r.BlockHash) == 0 {
//
// //记录未扫区块
// unscanRecord := NewUnscanRecord(height, r.TxID, "save to wallet failed.")
// err = bs.SaveUnscanRecord(unscanRecord)
// if err != nil {
// bs.wm.Log.Std.Error("block height: %d, txID: %s save unscan record failed. unexpected error: %v", height, r.TxID, err.Error())
// }
//
// } else {
// bs.wm.Log.Info("block scanner save blockHeight:", height, "txid:", r.TxID, "address:", r.Address, "successfully.")
// }
// } else {
// return errors.New("address in wallet is not found")
// }
//
// }
//
// return nil
//}
//GetScannedBlockHeader 获取当前扫描的区块头
func (bs *HNSBlockScanner) GetScannedBlockHeader() (*openwallet.BlockHeader, error) {
var (
blockHeight uint64 = 0
hash string
err error
)
blockHeight, hash, _ = bs.GetLocalNewBlock()
//如果本地没有记录,查询接口的高度
if blockHeight == 0 {
blockHeight, err = bs.wm.GetBlockHeight()
if err != nil {
return nil, err
}
//就上一个区块链为当前区块
blockHeight = blockHeight - 1
hash, err = bs.wm.GetBlockHash(blockHeight)
if err != nil {
return nil, err
}
}
return &openwallet.BlockHeader{Height: blockHeight, Hash: hash}, nil
}
//GetCurrentBlockHeader 获取当前区块高度
func (bs *HNSBlockScanner) GetCurrentBlockHeader() (*openwallet.BlockHeader, error) {
var (
blockHeight uint64 = 0
hash string
err error
)
blockHeight, err = bs.wm.GetBlockHeight()
if err != nil {
return nil, err
}
hash, err = bs.wm.GetBlockHash(blockHeight)
if err != nil {
return nil, err
}
return &openwallet.BlockHeader{Height: blockHeight, Hash: hash}, nil
}