-
-
Notifications
You must be signed in to change notification settings - Fork 746
Expand file tree
/
Copy pathworker.go
More file actions
2851 lines (2719 loc) · 93.4 KB
/
Copy pathworker.go
File metadata and controls
2851 lines (2719 loc) · 93.4 KB
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
package api
import (
"bytes"
"encoding/json"
"fmt"
"math"
"math/big"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/golang/glog"
"github.com/juju/errors"
"github.com/trezor/blockbook/bchain"
"github.com/trezor/blockbook/bchain/coins/eth"
"github.com/trezor/blockbook/common"
"github.com/trezor/blockbook/db"
"github.com/trezor/blockbook/fiat"
)
// Worker is handle to api worker
type Worker struct {
db *db.RocksDB
txCache *db.TxCache
chain bchain.BlockChain
chainParser bchain.BlockChainParser
chainType bchain.ChainType
useAddressAliases bool
mempool bchain.Mempool
is *common.InternalState
fiatRates *fiat.FiatRates
metrics *common.Metrics
xpubConfig XpubConfig
}
var getTickersForTimestamps = func(fr *fiat.FiatRates, timestamps []int64, vsCurrency string, token string) (*[]*common.CurrencyRatesTicker, error) {
return fr.GetTickersForTimestamps(timestamps, vsCurrency, token)
}
var getCurrentTicker = func(fr *fiat.FiatRates, vsCurrency string, token string) *common.CurrencyRatesTicker {
return fr.GetCurrentTicker(vsCurrency, token)
}
// contractInfoCache is a temporary cache of contract information for ethereum token transfers
type contractInfoCache = map[string]*bchain.ContractInfo
// NewWorker creates new api worker
func NewWorker(db *db.RocksDB, chain bchain.BlockChain, mempool bchain.Mempool, txCache *db.TxCache, metrics *common.Metrics, is *common.InternalState, fiatRates *fiat.FiatRates) (*Worker, error) {
// Resolve per-chain xpub config override, if any.
xpubCfg := DefaultXpubConfig()
if provider, ok := chain.(interface {
XpubConfigOverride() *bchain.XpubConfig
}); ok {
if override := provider.XpubConfigOverride(); override != nil {
xpubCfg = ApplyXpubConfig(override)
glog.Infof("xpub: xpubConfig override applied: maxCacheEntries=%d maxCacheExpirationSeconds=%d defaultAddressesGap=%d maxAddressesGap=%d",
xpubCfg.MaxCacheEntries, xpubCfg.MaxCacheExpirationSeconds, xpubCfg.DefaultAddressesGap, xpubCfg.MaxAddressesGap)
}
}
w := &Worker{
db: db,
txCache: txCache,
chain: chain,
chainParser: chain.GetChainParser(),
chainType: chain.GetChainParser().GetChainType(),
useAddressAliases: chain.GetChainParser().UseAddressAliases(),
mempool: mempool,
is: is,
fiatRates: fiatRates,
metrics: metrics,
xpubConfig: xpubCfg,
}
if w.chainType == bchain.ChainBitcoinType {
w.initXpubCache()
}
return w, nil
}
func (w *Worker) getAddressesFromVout(vout *bchain.Vout) (bchain.AddressDescriptor, []string, bool, error) {
addrDesc, err := w.chainParser.GetAddrDescFromVout(vout)
if err != nil {
return nil, nil, false, err
}
a, s, err := w.chainParser.GetAddressesFromAddrDesc(addrDesc)
return addrDesc, a, s, err
}
// setSpendingTxToVout is helper function, that finds transaction that spent given output and sets it to the output
// there is no direct index for the operation, it must be found using addresses -> txaddresses -> tx
func (w *Worker) setSpendingTxToVout(vout *Vout, txid string, height uint32) error {
err := w.db.GetAddrDescTransactions(vout.AddrDesc, height, maxUint32, func(t string, height uint32, indexes []int32) error {
for _, index := range indexes {
// take only inputs
if index < 0 {
index = ^index
tsp, err := w.db.GetTxAddresses(t)
if err != nil {
return err
} else if tsp == nil {
glog.Warning("DB inconsistency: tx ", t, ": not found in txAddresses")
} else if len(tsp.Inputs) > int(index) {
if tsp.Inputs[index].ValueSat.Cmp((*big.Int)(vout.ValueSat)) == 0 {
spentTx, spentHeight, err := w.txCache.GetTransaction(t)
if err != nil {
glog.Warning("Tx ", t, ": not found")
} else {
if len(spentTx.Vin) > int(index) {
if spentTx.Vin[index].Txid == txid {
vout.SpentTxID = t
vout.SpentHeight = int(spentHeight)
vout.SpentIndex = int(index)
return &db.StopIteration{}
}
}
}
}
}
}
}
return nil
})
return err
}
// GetSpendingTxid returns transaction id of transaction that spent given output
func (w *Worker) GetSpendingTxid(txid string, n int) (string, error) {
if w.db.HasExtendedIndex() {
tsp, err := w.db.GetTxAddresses(txid)
if err != nil {
return "", err
} else if tsp == nil {
glog.Warning("DB inconsistency: tx ", txid, ": not found in txAddresses")
return "", NewAPIError(fmt.Sprintf("Txid %v not found", txid), false)
}
if n >= len(tsp.Outputs) || n < 0 {
return "", NewAPIError(fmt.Sprintf("Passed incorrect vout index %v for tx %v, len vout %v", n, txid, len(tsp.Outputs)), false)
}
return tsp.Outputs[n].SpentTxid, nil
}
start := time.Now()
tx, err := w.getTransaction(txid, false, false, nil)
if err != nil {
return "", err
}
if n >= len(tx.Vout) || n < 0 {
return "", NewAPIError(fmt.Sprintf("Passed incorrect vout index %v for tx %v, len vout %v", n, tx.Txid, len(tx.Vout)), false)
}
err = w.setSpendingTxToVout(&tx.Vout[n], tx.Txid, uint32(tx.Blockheight))
if err != nil {
return "", err
}
glog.V(1).Info("GetSpendingTxid ", txid, " ", n, ", ", time.Since(start))
return tx.Vout[n].SpentTxID, nil
}
func aggregateAddress(m map[string]struct{}, a string) {
if m != nil && len(a) > 0 {
m[a] = struct{}{}
}
}
func aggregateAddresses(m map[string]struct{}, addresses []string, isAddress bool) {
if m != nil && isAddress {
for _, a := range addresses {
if len(a) > 0 {
m[a] = struct{}{}
}
}
}
}
func (w *Worker) newAddressesMapForAliases() map[string]struct{} {
// return non nil map only if the chain supports address aliases
if w.useAddressAliases {
return make(map[string]struct{})
}
// returning nil disables the processing of the address aliases
return nil
}
func (w *Worker) getTxChainExtraData(tx *bchain.Tx) (*TxChainExtraData, error) {
payload, err := w.chainParser.GetChainExtraData(tx)
if err != nil {
return nil, err
}
if len(payload) == 0 {
return nil, nil
}
return &TxChainExtraData{
PayloadType: w.chainParser.GetChainExtraPayloadType(),
Payload: payload,
}, nil
}
func (w *Worker) getAccountChainExtraData(addrDesc bchain.AddressDescriptor) (*AccountChainExtraData, error) {
payload, err := w.chain.GetAddressChainExtraData(addrDesc)
if err != nil {
return nil, err
}
if len(payload) == 0 {
return nil, nil
}
return &AccountChainExtraData{
PayloadType: w.chainParser.GetChainExtraPayloadType(),
Payload: payload,
}, nil
}
func (w *Worker) getAddressAliases(addresses map[string]struct{}) AddressAliasesMap {
if len(addresses) > 0 {
aliases := make(AddressAliasesMap)
var t string
if w.chainType == bchain.ChainEthereumType {
t = "ENS"
} else {
t = "Alias"
}
for a := range addresses {
if w.chainType == bchain.ChainEthereumType {
addrDesc, err := w.chainParser.GetAddrDescFromAddress(a)
if err != nil || addrDesc == nil {
continue
}
ci, err := w.db.GetContractInfo(addrDesc, bchain.UnknownTokenStandard)
if err == nil && ci != nil {
if ci.Standard == bchain.UnhandledTokenStandard {
ci, _, err = w.getContractDescriptorInfo(addrDesc, bchain.UnknownTokenStandard)
}
if err == nil && ci != nil && ci.Name != "" {
aliases[a] = AddressAlias{Type: "Contract", Alias: ci.Name}
}
}
}
n := w.db.GetAddressAlias(a)
if len(n) > 0 {
aliases[a] = AddressAlias{Type: t, Alias: n}
}
}
return aliases
}
return nil
}
// GetTransaction reads transaction data from txid
func (w *Worker) GetTransaction(txid string, spendingTxs bool, specificJSON bool) (*Tx, error) {
addresses := w.newAddressesMapForAliases()
tx, err := w.getTransaction(txid, spendingTxs, specificJSON, addresses)
if err != nil {
return nil, err
}
tx.AddressAliases = w.getAddressAliases(addresses)
return tx, nil
}
// GetRawTransaction gets raw transaction data in hex format from txid
func (w *Worker) GetRawTransaction(txid string) (string, error) {
return w.chain.EthereumTypeGetRawTransaction(txid)
}
// getTransaction reads transaction data from txid
func (w *Worker) getTransaction(txid string, spendingTxs bool, specificJSON bool, addresses map[string]struct{}) (*Tx, error) {
bchainTx, height, err := w.txCache.GetTransaction(txid)
if err != nil {
if err == bchain.ErrTxNotFound {
return nil, NewAPIError(fmt.Sprintf("Transaction '%v' not found", txid), true)
}
return nil, NewAPIError(fmt.Sprintf("Transaction '%v' not found (%v)", txid, err), true)
}
return w.GetTransactionFromBchainTx(bchainTx, height, spendingTxs, specificJSON, addresses)
}
func (w *Worker) getParsedEthereumInputData(data string) *bchain.EthereumParsedInputData {
var err error
var signatures *[]bchain.FourByteSignature
fourBytes := eth.GetSignatureFromData(data)
if fourBytes != 0 {
signatures, err = w.db.GetFourByteSignatures(fourBytes)
if err != nil {
glog.Errorf("GetFourByteSignatures(%v) error %v", fourBytes, err)
return nil
}
if signatures == nil {
return nil
}
}
return w.chainParser.ParseInputData(signatures, data)
}
// getConfirmationETA returns confirmation ETA in seconds and blocks
func (w *Worker) getConfirmationETA(tx *Tx) (int64, uint32) {
var etaBlocks uint32
var etaSeconds int64
if w.chainType == bchain.ChainBitcoinType && tx.FeesSat != nil {
_, _, mempoolSize := w.is.GetMempoolSyncState()
// if there are a few transactions in the mempool, the estimate fee does not work well
// and the tx is most probably going to be confirmed in the first block
if mempoolSize < 32 {
etaBlocks = 1
} else {
var txFeePerKB int64
if tx.VSize > 0 {
txFeePerKB = 1000 * tx.FeesSat.AsInt64() / int64(tx.VSize)
} else if tx.Size > 0 {
txFeePerKB = 1000 * tx.FeesSat.AsInt64() / int64(tx.Size)
}
if txFeePerKB > 0 {
// binary search the estimate, split it to more common first 7 blocks and the rest up to 70 blocks
var b int
fee, _ := w.cachedEstimateFee(7, true)
if fee.Int64() <= txFeePerKB {
b = sort.Search(7, func(i int) bool {
// fee is in sats/kB
fee, _ := w.cachedEstimateFee(i+1, true)
return fee.Int64() <= txFeePerKB
})
b += 1
} else {
b = sort.Search(63, func(i int) bool {
fee, _ := w.cachedEstimateFee(i+7, true)
return fee.Int64() <= txFeePerKB
})
b += 7
}
etaBlocks = uint32(b)
}
}
etaSeconds = int64(etaBlocks * w.is.AvgBlockPeriod)
}
return etaSeconds, etaBlocks
}
// GetTransactionFromBchainTx reads transaction data from txid
func (w *Worker) GetTransactionFromBchainTx(bchainTx *bchain.Tx, height int, spendingTxs bool, specificJSON bool, addresses map[string]struct{}) (*Tx, error) {
var err error
var ta *db.TxAddresses
var tokens []TokenTransfer
var ethSpecific *EthereumSpecific
var blockhash string
if bchainTx.Confirmations > 0 {
if w.chainType == bchain.ChainBitcoinType {
ta, err = w.db.GetTxAddresses(bchainTx.Txid)
if err != nil {
return nil, errors.Annotatef(err, "GetTxAddresses %v", bchainTx.Txid)
}
}
blockhash, err = w.db.GetBlockHash(uint32(height))
if err != nil {
return nil, errors.Annotatef(err, "GetBlockHash %v", height)
}
}
var valInSat, valOutSat, feesSat big.Int
var pValInSat *big.Int
vins := make([]Vin, len(bchainTx.Vin))
rbf := false
for i := range bchainTx.Vin {
bchainVin := &bchainTx.Vin[i]
vin := &vins[i]
vin.Txid = bchainVin.Txid
vin.N = i
vin.Vout = bchainVin.Vout
vin.Sequence = int64(bchainVin.Sequence)
// detect explicit Replace-by-Fee transactions as defined by BIP125
if bchainTx.Confirmations == 0 && bchainVin.Sequence < 0xffffffff-1 {
rbf = true
}
vin.Hex = bchainVin.ScriptSig.Hex
vin.Coinbase = bchainVin.Coinbase
if w.chainType == bchain.ChainBitcoinType {
// bchainVin.Txid=="" is coinbase transaction
if bchainVin.Txid != "" {
// load the spending address from TxAddresses; only the spent output
// is needed, so avoid unpacking the whole previous-tx record
output, err := w.db.GetTxAddressesOutput(bchainVin.Txid, vin.Vout)
if err != nil {
return nil, errors.Annotatef(err, "GetTxAddressesOutput %v", bchainVin.Txid)
}
if output == nil {
// try to load from backend
otx, _, err := w.txCache.GetTransaction(bchainVin.Txid)
if err != nil {
if err == bchain.ErrTxNotFound {
// try to get AddrDesc using coin specific handling and continue processing the tx
vin.AddrDesc = w.chainParser.GetAddrDescForUnknownInput(bchainTx, i)
vin.Addresses, vin.IsAddress, err = w.chainParser.GetAddressesFromAddrDesc(vin.AddrDesc)
if err != nil {
glog.Warning("GetAddressesFromAddrDesc tx ", bchainVin.Txid, ", addrDesc ", vin.AddrDesc, ": ", err)
}
aggregateAddresses(addresses, vin.Addresses, vin.IsAddress)
continue
}
return nil, errors.Annotatef(err, "txCache.GetTransaction %v", bchainVin.Txid)
}
// mempool transactions are not in TxAddresses but confirmed should be there, log a problem
// ignore when Confirmations==1, it may be just a timing problem
if bchainTx.Confirmations > 1 {
glog.Warning("DB inconsistency: tx ", bchainVin.Txid, ": not found in txAddresses, confirmations ", bchainTx.Confirmations)
}
if len(otx.Vout) > int(vin.Vout) {
vout := &otx.Vout[vin.Vout]
vin.ValueSat = (*Amount)(&vout.ValueSat)
vin.AddrDesc, vin.Addresses, vin.IsAddress, err = w.getAddressesFromVout(vout)
if err != nil {
glog.Errorf("getAddressesFromVout error %v, vout %+v", err, vout)
}
aggregateAddresses(addresses, vin.Addresses, vin.IsAddress)
}
} else {
vin.ValueSat = (*Amount)(&output.ValueSat)
vin.AddrDesc = output.AddrDesc
vin.Addresses, vin.IsAddress, err = output.Addresses(w.chainParser)
if err != nil {
glog.Errorf("output.Addresses error %v, tx %v, output %v", err, bchainVin.Txid, i)
}
aggregateAddresses(addresses, vin.Addresses, vin.IsAddress)
}
if vin.ValueSat != nil {
valInSat.Add(&valInSat, (*big.Int)(vin.ValueSat))
}
}
} else if w.chainType == bchain.ChainEthereumType {
if len(bchainVin.Addresses) > 0 {
vin.AddrDesc, err = w.chainParser.GetAddrDescFromAddress(bchainVin.Addresses[0])
if err != nil {
glog.Errorf("GetAddrDescFromAddress error %v, tx %v, bchainVin %v", err, bchainTx.Txid, bchainVin)
}
vin.Addresses = bchainVin.Addresses
vin.IsAddress = true
aggregateAddresses(addresses, vin.Addresses, vin.IsAddress)
}
}
}
vouts := make([]Vout, len(bchainTx.Vout))
for i := range bchainTx.Vout {
bchainVout := &bchainTx.Vout[i]
vout := &vouts[i]
vout.N = i
vout.ValueSat = (*Amount)(&bchainVout.ValueSat)
valOutSat.Add(&valOutSat, &bchainVout.ValueSat)
vout.Hex = bchainVout.ScriptPubKey.Hex
vout.AddrDesc, vout.Addresses, vout.IsAddress, err = w.getAddressesFromVout(bchainVout)
if err != nil {
glog.V(2).Infof("getAddressesFromVout error %v, %v, output %v", err, bchainTx.Txid, bchainVout.N)
}
aggregateAddresses(addresses, vout.Addresses, vout.IsAddress)
if ta != nil {
vout.Spent = ta.Outputs[i].Spent
if vout.Spent {
if w.db.HasExtendedIndex() {
vout.SpentTxID = ta.Outputs[i].SpentTxid
vout.SpentIndex = int(ta.Outputs[i].SpentIndex)
vout.SpentHeight = int(ta.Outputs[i].SpentHeight)
} else if spendingTxs {
err = w.setSpendingTxToVout(vout, bchainTx.Txid, uint32(height))
if err != nil {
glog.Errorf("setSpendingTxToVout error %v, %v, output %v", err, vout.AddrDesc, vout.N)
}
}
}
}
}
if w.chainType == bchain.ChainBitcoinType {
// for coinbase transactions valIn is 0
feesSat.Sub(&valInSat, &valOutSat)
if feesSat.Sign() == -1 {
feesSat.SetUint64(0)
}
pValInSat = &valInSat
} else if w.chainType == bchain.ChainEthereumType {
tokenTransfers, err := w.chainParser.EthereumTypeGetTokenTransfersFromTx(bchainTx)
if err != nil {
glog.Errorf("GetTokenTransfersFromTx error %v, %v", err, bchainTx)
}
tokens = w.getEthereumTokensTransfers(tokenTransfers, addresses)
ethTxData := w.chainParser.GetEthereumTxData(bchainTx)
var internalData *bchain.EthereumInternalData
if bchain.ProcessInternalTransactions {
internalData, err = w.db.GetEthereumInternalData(bchainTx.Txid)
if err != nil {
return nil, err
}
}
parsedInputData := w.getParsedEthereumInputData(ethTxData.Data)
feesSat = *getEthereumFeesSat(ethTxData)
if len(bchainTx.Vout) > 0 {
valOutSat = bchainTx.Vout[0].ValueSat
}
ethSpecific = &EthereumSpecific{
GasLimit: ethTxData.GasLimit,
GasPrice: (*Amount)(ethTxData.GasPrice),
EffectiveGasPrice: (*Amount)(ethTxData.EffectiveGasPrice),
MaxPriorityFeePerGas: (*Amount)(ethTxData.MaxPriorityFeePerGas),
MaxFeePerGas: (*Amount)(ethTxData.MaxFeePerGas),
BaseFeePerGas: (*Amount)(ethTxData.BaseFeePerGas),
GasUsed: ethTxData.GasUsed,
L1Fee: ethTxData.L1Fee,
L1FeeScalar: ethTxData.L1FeeScalar,
L1GasPrice: (*Amount)(ethTxData.L1GasPrice),
L1GasUsed: ethTxData.L1GasUsed,
Nonce: ethTxData.Nonce,
Status: ethTxData.Status,
Data: ethTxData.Data,
ParsedData: parsedInputData,
}
if internalData != nil {
ethSpecific.Type = internalData.Type
ethSpecific.CreatedContract = internalData.Contract
ethSpecific.Error = internalData.Error
ethSpecific.InternalTransfers = make([]EthereumInternalTransfer, len(internalData.Transfers))
for i := range internalData.Transfers {
f := &internalData.Transfers[i]
t := ðSpecific.InternalTransfers[i]
t.From = f.From
aggregateAddress(addresses, t.From)
t.To = f.To
aggregateAddress(addresses, t.To)
t.Type = f.Type
t.Value = (*Amount)(&f.Value)
}
}
}
var sj json.RawMessage
var chainExtraData *TxChainExtraData
// return CoinSpecificData for all mempool transactions or if requested
if specificJSON || bchainTx.Confirmations == 0 {
sj, err = w.chain.GetTransactionSpecific(bchainTx)
if err != nil {
return nil, err
}
}
chainExtraData, err = w.getTxChainExtraData(bchainTx)
if err != nil {
glog.Warningf("GetTxChainExtraData error %v, %v", err, bchainTx)
}
r := &Tx{
Blockhash: blockhash,
Blockheight: height,
Blocktime: bchainTx.Blocktime,
Confirmations: bchainTx.Confirmations,
FeesSat: (*Amount)(&feesSat),
Locktime: bchainTx.LockTime,
Txid: bchainTx.Txid,
ValueInSat: (*Amount)(pValInSat),
ValueOutSat: (*Amount)(&valOutSat),
Version: bchainTx.Version,
Size: len(bchainTx.Hex) >> 1,
VSize: int(bchainTx.VSize),
Hex: bchainTx.Hex,
Rbf: rbf,
Vin: vins,
Vout: vouts,
CoinSpecificData: sj,
ChainExtraData: chainExtraData,
TokenTransfers: tokens,
EthereumSpecific: ethSpecific,
}
if bchainTx.Confirmations == 0 {
r.Blocktime = int64(w.mempool.GetTransactionTime(bchainTx.Txid))
r.ConfirmationETASeconds, r.ConfirmationETABlocks = w.getConfirmationETA(r)
}
return r, nil
}
// GetTransactionFromMempoolTx converts bchain.MempoolTx to Tx, with limited amount of data
// it is not doing any request to backend or to db
func (w *Worker) GetTransactionFromMempoolTx(mempoolTx *bchain.MempoolTx) (*Tx, error) {
var err error
var valInSat, valOutSat, feesSat big.Int
var pValInSat *big.Int
var tokens []TokenTransfer
var ethSpecific *EthereumSpecific
var chainExtraData *TxChainExtraData
addresses := w.newAddressesMapForAliases()
vins := make([]Vin, len(mempoolTx.Vin))
rbf := false
for i := range mempoolTx.Vin {
bchainVin := &mempoolTx.Vin[i]
vin := &vins[i]
vin.Txid = bchainVin.Txid
vin.N = i
vin.Vout = bchainVin.Vout
vin.Sequence = int64(bchainVin.Sequence)
// detect explicit Replace-by-Fee transactions as defined by BIP125
if bchainVin.Sequence < 0xffffffff-1 {
rbf = true
}
vin.Hex = bchainVin.ScriptSig.Hex
vin.Coinbase = bchainVin.Coinbase
if w.chainType == bchain.ChainBitcoinType {
// bchainVin.Txid=="" is coinbase transaction
if bchainVin.Txid != "" {
vin.ValueSat = (*Amount)(&bchainVin.ValueSat)
vin.AddrDesc = bchainVin.AddrDesc
vin.Addresses, vin.IsAddress, _ = w.chainParser.GetAddressesFromAddrDesc(vin.AddrDesc)
if vin.ValueSat != nil {
valInSat.Add(&valInSat, (*big.Int)(vin.ValueSat))
}
aggregateAddresses(addresses, vin.Addresses, vin.IsAddress)
}
} else if w.chainType == bchain.ChainEthereumType {
if len(bchainVin.Addresses) > 0 {
vin.AddrDesc, err = w.chainParser.GetAddrDescFromAddress(bchainVin.Addresses[0])
if err != nil {
glog.Errorf("GetAddrDescFromAddress error %v, tx %v, bchainVin %v", err, mempoolTx.Txid, bchainVin)
}
vin.Addresses = bchainVin.Addresses
vin.IsAddress = true
aggregateAddresses(addresses, vin.Addresses, vin.IsAddress)
}
}
}
vouts := make([]Vout, len(mempoolTx.Vout))
for i := range mempoolTx.Vout {
bchainVout := &mempoolTx.Vout[i]
vout := &vouts[i]
vout.N = i
vout.ValueSat = (*Amount)(&bchainVout.ValueSat)
valOutSat.Add(&valOutSat, &bchainVout.ValueSat)
vout.Hex = bchainVout.ScriptPubKey.Hex
vout.AddrDesc, vout.Addresses, vout.IsAddress, err = w.getAddressesFromVout(bchainVout)
if err != nil {
glog.V(2).Infof("getAddressesFromVout error %v, %v, output %v", err, mempoolTx.Txid, bchainVout.N)
}
aggregateAddresses(addresses, vout.Addresses, vout.IsAddress)
}
if w.chainType == bchain.ChainBitcoinType {
// for coinbase transactions valIn is 0
feesSat.Sub(&valInSat, &valOutSat)
if feesSat.Sign() == -1 {
feesSat.SetUint64(0)
}
pValInSat = &valInSat
} else if w.chainType == bchain.ChainEthereumType {
if len(mempoolTx.Vout) > 0 {
valOutSat = mempoolTx.Vout[0].ValueSat
}
tokens = w.getEthereumTokensTransfers(mempoolTx.TokenTransfers, addresses)
ethTxData := w.chainParser.GetEthereumTxData(&bchain.Tx{
Txid: mempoolTx.Txid,
CoinSpecificData: mempoolTx.CoinSpecificData,
})
ethSpecific = &EthereumSpecific{
GasLimit: ethTxData.GasLimit,
GasPrice: (*Amount)(ethTxData.GasPrice),
MaxPriorityFeePerGas: (*Amount)(ethTxData.MaxPriorityFeePerGas),
MaxFeePerGas: (*Amount)(ethTxData.MaxFeePerGas),
BaseFeePerGas: (*Amount)(ethTxData.BaseFeePerGas),
GasUsed: ethTxData.GasUsed,
Nonce: ethTxData.Nonce,
Status: ethTxData.Status,
Data: ethTxData.Data,
}
}
chainExtraData, err = w.getTxChainExtraData(&bchain.Tx{
Txid: mempoolTx.Txid,
CoinSpecificData: mempoolTx.CoinSpecificData,
})
if err != nil {
glog.Warningf("GetTxChainExtraData error %v, %v", err, mempoolTx.Txid)
}
r := &Tx{
Blocktime: mempoolTx.Blocktime,
FeesSat: (*Amount)(&feesSat),
Locktime: mempoolTx.LockTime,
Txid: mempoolTx.Txid,
ValueInSat: (*Amount)(pValInSat),
ValueOutSat: (*Amount)(&valOutSat),
Version: mempoolTx.Version,
Size: len(mempoolTx.Hex) >> 1,
VSize: int(mempoolTx.VSize),
Hex: mempoolTx.Hex,
Rbf: rbf,
Vin: vins,
Vout: vouts,
ChainExtraData: chainExtraData,
TokenTransfers: tokens,
EthereumSpecific: ethSpecific,
AddressAliases: w.getAddressAliases(addresses),
}
r.ConfirmationETASeconds, r.ConfirmationETABlocks = w.getConfirmationETA(r)
return r, nil
}
func (w *Worker) GetContractInfo(contract string, standardFromContext bchain.TokenStandardName) (*bchain.ContractInfo, bool, error) {
cd, err := w.chainParser.GetAddrDescFromAddress(contract)
if err != nil {
return nil, false, err
}
return w.getContractDescriptorInfo(cd, standardFromContext)
}
func (w *Worker) getContractDescriptorInfo(cd bchain.AddressDescriptor, standardFromContext bchain.TokenStandardName) (*bchain.ContractInfo, bool, error) {
var err error
validContract := true
contractInfo, err := w.db.GetContractInfo(cd, standardFromContext)
if err != nil {
return nil, false, err
}
if contractInfo == nil {
// log warning only if the contract should have been known from processing of the internal data
if bchain.ProcessInternalTransactions {
glog.Warningf("Contract %v %v not found in DB", cd, standardFromContext)
}
contractInfo, err = w.chain.GetContractInfo(cd)
if err != nil {
glog.Errorf("GetContractInfo from chain error %v, contract %v", err, cd)
}
if contractInfo == nil {
contractInfo = &bchain.ContractInfo{Standard: bchain.UnknownTokenStandard, Decimals: w.chainParser.AmountDecimals()}
addresses, _, _ := w.chainParser.GetAddressesFromAddrDesc(cd)
if len(addresses) > 0 {
contractInfo.Contract = addresses[0]
}
validContract = false
} else {
if standardFromContext != bchain.UnknownTokenStandard && contractInfo.Standard == bchain.UnknownTokenStandard {
contractInfo.Standard = standardFromContext
contractInfo.Type = standardFromContext
}
if err = w.db.StoreContractInfo(contractInfo); err != nil {
glog.Errorf("StoreContractInfo error %v, contract %v", err, cd)
}
}
} else if (contractInfo.Standard == bchain.UnhandledTokenStandard || len(contractInfo.Name) > 0 && contractInfo.Name[0] == 0) || (len(contractInfo.Symbol) > 0 && contractInfo.Symbol[0] == 0) {
// fix contract name/symbol that was parsed as a string consisting of zeroes
blockchainContractInfo, err := w.chain.GetContractInfo(cd)
if err != nil {
glog.Errorf("GetContractInfo from chain error %v, contract %v", err, cd)
} else {
if blockchainContractInfo != nil && len(blockchainContractInfo.Name) > 0 && blockchainContractInfo.Name[0] != 0 {
contractInfo.Name = blockchainContractInfo.Name
} else {
contractInfo.Name = ""
}
if blockchainContractInfo != nil && len(blockchainContractInfo.Symbol) > 0 && blockchainContractInfo.Symbol[0] != 0 {
contractInfo.Symbol = blockchainContractInfo.Symbol
} else {
contractInfo.Symbol = ""
}
if blockchainContractInfo != nil {
contractInfo.Decimals = blockchainContractInfo.Decimals
} else if contractInfo.Decimals == 0 && contractInfo.Standard == bchain.UnhandledTokenStandard {
// contract metadata could not be read on-chain; fall back to the coin's
// default decimals (18 for ERC-20) instead of persisting an ambiguous 0
// for a token whose true precision is simply unknown (trezor/blockbook#1577)
contractInfo.Decimals = w.chainParser.AmountDecimals()
}
if contractInfo.Standard == bchain.UnhandledTokenStandard {
glog.Infof("Contract %v %v [%s] handled", cd, standardFromContext, contractInfo.Name)
contractInfo.Standard = standardFromContext
contractInfo.Type = standardFromContext
}
if err = w.db.StoreContractInfo(contractInfo); err != nil {
glog.Errorf("StoreContractInfo error %v, contract %v", err, cd)
}
}
}
// never surface an unresolved contract (still Unhandled because its metadata
// could not be fetched, e.g. a transient RPC error above) with a bare 0
// decimals; use the coin default instead. Genuinely 0-decimal tokens always
// carry a resolved (handled) standard, so they are unaffected (trezor/blockbook#1577)
if contractInfo.Decimals == 0 && contractInfo.Standard == bchain.UnhandledTokenStandard {
contractInfo.Decimals = w.chainParser.AmountDecimals()
}
return contractInfo, validContract, nil
}
func (w *Worker) getEthereumTokensTransfers(transfers bchain.TokenTransfers, addresses map[string]struct{}) []TokenTransfer {
tokens := make([]TokenTransfer, len(transfers))
if len(transfers) > 0 {
sort.Sort(transfers)
contractCache := make(contractInfoCache)
for i := range transfers {
t := transfers[i]
standard := bchain.EthereumTokenStandardMap[t.Standard]
var contractInfo *bchain.ContractInfo
if info, ok := contractCache[t.Contract]; ok {
contractInfo = info
} else {
info, _, err := w.GetContractInfo(t.Contract, standard)
if err != nil {
glog.Errorf("getContractInfo error %v, contract %v", err, t.Contract)
continue
}
contractInfo = info
contractCache[t.Contract] = info
}
var value *Amount
var values []MultiTokenValue
if t.Standard == bchain.MultiToken {
values = make([]MultiTokenValue, len(t.MultiTokenValues))
for j := range values {
values[j].Id = (*Amount)(&t.MultiTokenValues[j].Id)
values[j].Value = (*Amount)(&t.MultiTokenValues[j].Value)
}
} else {
value = (*Amount)(&t.Value)
}
aggregateAddress(addresses, t.From)
aggregateAddress(addresses, t.To)
tokens[i] = TokenTransfer{
Type: standard,
Standard: standard,
Contract: t.Contract,
From: t.From,
To: t.To,
Value: value,
MultiTokenValues: values,
Decimals: contractInfo.Decimals,
Name: contractInfo.Name,
Symbol: contractInfo.Symbol,
}
}
}
return tokens
}
func (w *Worker) GetEthereumTokenURI(contract string, id string) (string, *bchain.ContractInfo, error) {
cd, err := w.chainParser.GetAddrDescFromAddress(contract)
if err != nil {
return "", nil, err
}
tokenId, ok := new(big.Int).SetString(id, 10)
if !ok {
return "", nil, errors.New("Invalid token id")
}
uri, err := w.chain.GetTokenURI(cd, tokenId)
if err != nil {
return "", nil, err
}
ci, _, err := w.getContractDescriptorInfo(cd, bchain.UnknownTokenStandard)
if err != nil {
return "", nil, err
}
return uri, ci, nil
}
func (w *Worker) getAddressTxids(addrDesc bchain.AddressDescriptor, mempool bool, filter *AddressFilter, maxResults int) ([]string, error) {
var err error
txids := make([]string, 0, 4)
var callback db.GetTransactionsCallback
if filter.Vout == AddressFilterVoutOff {
callback = func(txid string, height uint32, indexes []int32) error {
txids = append(txids, txid)
if len(txids) >= maxResults {
return &db.StopIteration{}
}
return nil
}
} else {
callback = func(txid string, height uint32, indexes []int32) error {
for _, index := range indexes {
vout := index
if vout < 0 {
vout = ^vout
}
if (filter.Vout == AddressFilterVoutInputs && index < 0) ||
(filter.Vout == AddressFilterVoutOutputs && index >= 0) ||
(vout == int32(filter.Vout)) {
txids = append(txids, txid)
if len(txids) >= maxResults {
return &db.StopIteration{}
}
break
}
}
return nil
}
}
if mempool {
uniqueTxs := make(map[string]struct{})
o, err := w.mempool.GetAddrDescTransactions(addrDesc)
if err != nil {
return nil, err
}
for _, m := range o {
if _, found := uniqueTxs[m.Txid]; !found {
l := len(txids)
callback(m.Txid, 0, []int32{m.Vout})
if len(txids) > l {
uniqueTxs[m.Txid] = struct{}{}
}
}
}
} else {
to := filter.ToHeight
if to == 0 {
to = maxUint32
}
err = w.db.GetAddrDescTransactions(addrDesc, filter.FromHeight, to, callback)
if err != nil {
return nil, err
}
}
return txids, nil
}
func (t *Tx) getAddrVoutValue(addrDesc bchain.AddressDescriptor) *big.Int {
var val big.Int
for _, vout := range t.Vout {
if bytes.Equal(vout.AddrDesc, addrDesc) && vout.ValueSat != nil {
val.Add(&val, (*big.Int)(vout.ValueSat))
}
}
return &val
}
func (t *Tx) getAddrEthereumTypeMempoolInputValue(addrDesc bchain.AddressDescriptor) *big.Int {
var val big.Int
if len(t.Vin) > 0 && len(t.Vout) > 0 && bytes.Equal(t.Vin[0].AddrDesc, addrDesc) {
val.Add(&val, (*big.Int)(t.Vout[0].ValueSat))
// add maximum possible fee (the used value is not yet known)
if t.EthereumSpecific != nil && t.EthereumSpecific.GasLimit != nil && t.EthereumSpecific.GasPrice != nil {
var fees big.Int
fees.Mul((*big.Int)(t.EthereumSpecific.GasPrice), t.EthereumSpecific.GasLimit)
val.Add(&val, &fees)
}
}
return &val
}
func (t *Tx) getAddrVinValue(addrDesc bchain.AddressDescriptor) *big.Int {
var val big.Int
for _, vin := range t.Vin {
if bytes.Equal(vin.AddrDesc, addrDesc) && vin.ValueSat != nil {
val.Add(&val, (*big.Int)(vin.ValueSat))
}
}
return &val
}
// GetUniqueTxids removes duplicate transactions
func GetUniqueTxids(txids []string) []string {
ut := make([]string, len(txids))
txidsMap := make(map[string]struct{})
i := 0
for _, txid := range txids {
_, e := txidsMap[txid]
if !e {
ut[i] = txid
i++
txidsMap[txid] = struct{}{}
}
}
return ut[0:i]
}
func (w *Worker) txFromTxAddress(txid string, ta *db.TxAddresses, bi *db.BlockInfo, bestheight uint32, addresses map[string]struct{}) *Tx {
var err error
var valInSat, valOutSat, feesSat big.Int
vins := make([]Vin, len(ta.Inputs))
for i := range ta.Inputs {
tai := &ta.Inputs[i]
vin := &vins[i]
vin.N = i
vin.ValueSat = (*Amount)(&tai.ValueSat)
valInSat.Add(&valInSat, &tai.ValueSat)
vin.Addresses, vin.IsAddress, err = tai.Addresses(w.chainParser)
if err != nil {
glog.Errorf("tai.Addresses error %v, tx %v, input %v, tai %+v", err, txid, i, tai)
}
if w.db.HasExtendedIndex() {
vin.Txid = tai.Txid
vin.Vout = tai.Vout
}
aggregateAddresses(addresses, vin.Addresses, vin.IsAddress)
}
vouts := make([]Vout, len(ta.Outputs))
for i := range ta.Outputs {
tao := &ta.Outputs[i]
vout := &vouts[i]
vout.N = i
vout.ValueSat = (*Amount)(&tao.ValueSat)
valOutSat.Add(&valOutSat, &tao.ValueSat)
vout.Addresses, vout.IsAddress, err = tao.Addresses(w.chainParser)
if err != nil {
glog.Errorf("tai.Addresses error %v, tx %v, output %v, tao %+v", err, txid, i, tao)
}
vout.Spent = tao.Spent
if vout.Spent && w.db.HasExtendedIndex() {
vout.SpentTxID = tao.SpentTxid
vout.SpentIndex = int(tao.SpentIndex)
vout.SpentHeight = int(tao.SpentHeight)
}
aggregateAddresses(addresses, vout.Addresses, vout.IsAddress)
}
// for coinbase transactions valIn is 0
feesSat.Sub(&valInSat, &valOutSat)
if feesSat.Sign() == -1 {
feesSat.SetUint64(0)
}