/
tx_decode.go
1868 lines (1518 loc) · 57.8 KB
/
tx_decode.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 syscoin
import (
"encoding/hex"
"errors"
"fmt"
"github.com/blocktree/go-owcdrivers/btcTransaction"
"github.com/blocktree/go-owcdrivers/omniTransaction"
"github.com/blocktree/openwallet/v2/common"
"github.com/blocktree/openwallet/v2/openwallet"
"github.com/shopspring/decimal"
"sort"
"strings"
"time"
)
type TransactionDecoder struct {
openwallet.TransactionDecoderBase
wm *WalletManager //钱包管理者
}
//NewTransactionDecoder 交易单解析器
func NewTransactionDecoder(wm *WalletManager) *TransactionDecoder {
decoder := TransactionDecoder{}
decoder.wm = wm
return &decoder
}
//CreateRawTransaction 创建交易单
func (decoder *TransactionDecoder) CreateRawTransaction(wrapper openwallet.WalletDAI, rawTx *openwallet.RawTransaction) error {
if rawTx.Coin.IsContract {
return decoder.CreateOmniRawTransaction(wrapper, rawTx)
} else {
return decoder.CreateBTCRawTransaction(wrapper, rawTx)
}
}
//SignRawTransaction 签名交易单
func (decoder *TransactionDecoder) SignRawTransaction(wrapper openwallet.WalletDAI, rawTx *openwallet.RawTransaction) error {
if rawTx.Coin.IsContract {
return decoder.SignOmniRawTransaction(wrapper, rawTx)
} else {
return decoder.SignBTCRawTransaction(wrapper, rawTx)
}
}
//VerifyRawTransaction 验证交易单,验证交易单并返回加入签名后的交易单
func (decoder *TransactionDecoder) VerifyRawTransaction(wrapper openwallet.WalletDAI, rawTx *openwallet.RawTransaction) error {
if rawTx.Coin.IsContract {
return decoder.VerifyOmniRawTransaction(wrapper, rawTx)
} else {
return decoder.VerifyBTCRawTransaction(wrapper, rawTx)
}
}
//CreateSummaryRawTransaction 创建汇总交易,返回原始交易单数组
func (decoder *TransactionDecoder) CreateSummaryRawTransaction(wrapper openwallet.WalletDAI, sumRawTx *openwallet.SummaryRawTransaction) ([]*openwallet.RawTransaction, error) {
var (
rawTxWithErrArray []*openwallet.RawTransactionWithError
rawTxArray = make([]*openwallet.RawTransaction, 0)
err error
)
if sumRawTx.Coin.IsContract {
rawTxWithErrArray, err = decoder.CreateOmniSummaryRawTransaction(wrapper, sumRawTx)
} else {
rawTxWithErrArray, err = decoder.CreateBTCSummaryRawTransaction(wrapper, sumRawTx)
}
if err != nil {
return nil, err
}
for _, rawTxWithErr := range rawTxWithErrArray {
if rawTxWithErr.Error != nil {
continue
}
rawTxArray = append(rawTxArray, rawTxWithErr.RawTx)
}
return rawTxArray, nil
}
//SendRawTransaction 广播交易单
func (decoder *TransactionDecoder) SubmitRawTransaction(wrapper openwallet.WalletDAI, rawTx *openwallet.RawTransaction) (*openwallet.Transaction, error) {
if len(rawTx.RawHex) == 0 {
return nil, fmt.Errorf("transaction hex is empty")
}
if !rawTx.IsCompleted {
return nil, fmt.Errorf("transaction is not completed validation")
}
txid, err := decoder.wm.SendRawTransaction(rawTx.RawHex)
if err != nil {
decoder.wm.Log.Warningf("[Sid: %s] submit raw hex: %s", rawTx.Sid, rawTx.RawHex)
return nil, err
}
rawTx.TxID = txid
rawTx.IsSubmit = true
decimals := int32(0)
fees := "0"
if rawTx.Coin.IsContract {
decimals = int32(rawTx.Coin.Contract.Decimals)
fees = "0"
} else {
decimals = int32(decoder.wm.Decimal())
fees = rawTx.Fees
}
//记录一个交易单
tx := &openwallet.Transaction{
From: rawTx.TxFrom,
To: rawTx.TxTo,
Amount: rawTx.TxAmount,
Coin: rawTx.Coin,
TxID: rawTx.TxID,
Decimal: decimals,
AccountID: rawTx.Account.AccountID,
Fees: fees,
SubmitTime: time.Now().Unix(),
}
tx.WxID = openwallet.GenTransactionWxID(tx)
return tx, nil
}
////////////////////////// BTC implement //////////////////////////
//CreateRawTransaction 创建交易单
func (decoder *TransactionDecoder) CreateBTCRawTransaction(wrapper openwallet.WalletDAI, rawTx *openwallet.RawTransaction) error {
var (
usedUTXO []*Unspent
outputAddrs = make(map[string]decimal.Decimal)
balance = decimal.New(0, 0)
totalSend = decimal.New(0, 0)
actualFees = decimal.New(0, 0)
feesRate = decimal.New(0, 0)
accountID = rawTx.Account.AccountID
destinations = make([]string, 0)
//accountTotalSent = decimal.Zero
limit = 2000
)
address, err := wrapper.GetAddressList(0, limit, "AccountID", rawTx.Account.AccountID)
if err != nil {
return err
}
if len(address) == 0 {
return openwallet.Errorf(openwallet.ErrAccountNotAddress, "[%s] have not addresses", accountID)
//return fmt.Errorf("[%s] have not addresses", accountID)
}
searchAddrs := make([]string, 0)
for _, address := range address {
searchAddrs = append(searchAddrs, address.Address)
}
//decoder.wm.Log.Debug(searchAddrs)
//查找账户的utxo
unspents, err := decoder.wm.ListUnspent(0, searchAddrs...)
if err != nil {
return err
}
if len(unspents) == 0 {
return openwallet.Errorf(openwallet.ErrInsufficientBalanceOfAccount, "[%s] balance is not enough", accountID)
}
if len(rawTx.To) == 0 {
return errors.New("Receiver addresses is empty!")
}
//计算总发送金额
for addr, amount := range rawTx.To {
deamount, _ := decimal.NewFromString(amount)
totalSend = totalSend.Add(deamount)
destinations = append(destinations, addr)
//计算账户的实际转账amount
//addresses, findErr := wrapper.GetAddressList(0, -1, "AccountID", rawTx.Account.AccountID, "Address", addr)
//if findErr != nil || len(addresses) == 0 {
// amountDec, _ := decimal.NewFromString(amount)
// accountTotalSent = accountTotalSent.Add(amountDec)
//}
}
//获取utxo,按小到大排序
sort.Sort(UnspentSort{unspents, func(a, b *Unspent) int {
a_amount, _ := decimal.NewFromString(a.Amount)
b_amount, _ := decimal.NewFromString(b.Amount)
if a_amount.GreaterThan(b_amount) {
return 1
} else {
return -1
}
}})
if len(rawTx.FeeRate) == 0 {
feesRate, err = decoder.wm.EstimateFeeRate()
if err != nil {
return err
}
} else {
feesRate, _ = decimal.NewFromString(rawTx.FeeRate)
}
decoder.wm.Log.Info("Calculating wallet unspent record to build transaction...")
computeTotalSend := totalSend
//循环的计算余额是否足够支付发送数额+手续费
for {
usedUTXO = make([]*Unspent, 0)
balance = decimal.New(0, 0)
//计算一个可用于支付的余额
for _, u := range unspents {
if u.Spendable {
ua, _ := decimal.NewFromString(u.Amount)
balance = balance.Add(ua)
usedUTXO = append(usedUTXO, u)
if balance.GreaterThanOrEqual(computeTotalSend) {
break
}
}
}
if balance.LessThan(computeTotalSend) {
return openwallet.Errorf(openwallet.ErrInsufficientBalanceOfAccount, "The balance: %s is not enough! ", balance.StringFixed(decoder.wm.Decimal()))
}
//计算手续费,找零地址有2个,一个是发送,一个是新创建的
fees, err := decoder.wm.EstimateFee(int64(len(usedUTXO)), int64(len(destinations)+1), feesRate)
if err != nil {
return err
}
//如果要手续费有发送支付,得计算加入手续费后,计算余额是否足够
//总共要发送的
computeTotalSend = totalSend.Add(fees)
if computeTotalSend.GreaterThan(balance) {
continue
}
computeTotalSend = totalSend
actualFees = fees
break
}
//UTXO如果大于设定限制,则分拆成多笔交易单发送
if len(usedUTXO) > decoder.wm.Config.MaxTxInputs {
errStr := fmt.Sprintf("The transaction is use max inputs over: %d", decoder.wm.Config.MaxTxInputs)
return errors.New(errStr)
}
//取账户最后一个地址
changeAddress := usedUTXO[0].Address
changeAmount := balance.Sub(computeTotalSend).Sub(actualFees)
rawTx.FeeRate = feesRate.StringFixed(decoder.wm.Decimal())
rawTx.Fees = actualFees.StringFixed(decoder.wm.Decimal())
decoder.wm.Log.Std.Notice("-----------------------------------------------")
decoder.wm.Log.Std.Notice("From Account: %s", accountID)
decoder.wm.Log.Std.Notice("To Address: %s", strings.Join(destinations, ", "))
decoder.wm.Log.Std.Notice("Use: %v", balance.StringFixed(decoder.wm.Decimal()))
decoder.wm.Log.Std.Notice("Fees: %v", actualFees.StringFixed(decoder.wm.Decimal()))
decoder.wm.Log.Std.Notice("Receive: %v", computeTotalSend.StringFixed(decoder.wm.Decimal()))
decoder.wm.Log.Std.Notice("Change: %v", changeAmount.StringFixed(decoder.wm.Decimal()))
decoder.wm.Log.Std.Notice("Change Address: %v", changeAddress)
decoder.wm.Log.Std.Notice("-----------------------------------------------")
//装配输出
for to, amount := range rawTx.To {
decamount, _ := decimal.NewFromString(amount)
outputAddrs = appendOutput(outputAddrs, to, decamount)
//outputAddrs[to] = amount
}
//changeAmount := balance.Sub(totalSend).Sub(actualFees)
if changeAmount.GreaterThan(decimal.New(0, 0)) {
outputAddrs = appendOutput(outputAddrs, changeAddress, changeAmount)
//outputAddrs[changeAddress] = changeAmount.StringFixed(decoder.wm.Decimal())
}
err = decoder.createBTCRawTransaction(wrapper, rawTx, usedUTXO, outputAddrs)
if err != nil {
return err
}
return nil
}
//SignRawTransaction 签名交易单
func (decoder *TransactionDecoder) SignBTCRawTransaction(wrapper openwallet.WalletDAI, rawTx *openwallet.RawTransaction) error {
if rawTx.Signatures == nil || len(rawTx.Signatures) == 0 {
//this.wm.Log.Std.Error("len of signatures error. ")
return fmt.Errorf("transaction signature is empty")
}
key, err := wrapper.HDKey()
if err != nil {
return err
}
keySignatures := rawTx.Signatures[rawTx.Account.AccountID]
if keySignatures != nil {
for _, keySignature := range keySignatures {
childKey, err := key.DerivedKeyWithPath(keySignature.Address.HDPath, keySignature.EccType)
keyBytes, err := childKey.GetPrivateKeyBytes()
if err != nil {
return err
}
decoder.wm.Log.Debug("privateKey:", hex.EncodeToString(keyBytes))
//privateKeys = append(privateKeys, keyBytes)
txHash := btcTransaction.TxHash{
Hash: keySignature.Message,
Normal: &btcTransaction.NormalTx{
Address: keySignature.Address.Address,
SigType: btcTransaction.SigHashAll,
},
}
//transHash = append(transHash, txHash)
decoder.wm.Log.Debug("hash:", txHash.GetTxHashHex())
//签名交易
/////////交易单哈希签名
sigPub, err := btcTransaction.SignRawTransactionHash(txHash.GetTxHashHex(), keyBytes)
if err != nil {
return fmt.Errorf("transaction hash sign failed, unexpected error: %v", err)
} else {
//for i, s := range sigPub {
// decoder.wm.Log.Info("第", i+1, "个签名结果")
// decoder.wm.Log.Info()
// decoder.wm.Log.Info("对应的公钥为")
// decoder.wm.Log.Info(hex.EncodeToString(s.Pubkey))
//}
//txHash.Normal.SigPub = *sigPub
}
keySignature.Signature = hex.EncodeToString(sigPub.Signature)
}
}
decoder.wm.Log.Info("transaction hash sign success")
rawTx.Signatures[rawTx.Account.AccountID] = keySignatures
//decoder.wm.Log.Info("rawTx.Signatures 1:", rawTx.Signatures)
return nil
}
//VerifyRawTransaction 验证交易单,验证交易单并返回加入签名后的交易单
func (decoder *TransactionDecoder) VerifyBTCRawTransaction(wrapper openwallet.WalletDAI, rawTx *openwallet.RawTransaction) error {
//先加载是否有配置文件
//err := decoder.wm.LoadConfig()
//if err != nil {
// return err
//}
var (
txUnlocks = make([]btcTransaction.TxUnlock, 0)
emptyTrans = rawTx.RawHex
//sigPub = make([]btcTransaction.SignaturePubkey, 0)
transHash = make([]btcTransaction.TxHash, 0)
addressPrefix btcTransaction.AddressPrefix
)
if rawTx.Signatures == nil || len(rawTx.Signatures) == 0 {
//this.wm.Log.Std.Error("len of signatures error. ")
return fmt.Errorf("transaction signature is empty")
}
//TODO:待支持多重签名
for accountID, keySignatures := range rawTx.Signatures {
decoder.wm.Log.Debug("accountID Signatures:", accountID)
for _, keySignature := range keySignatures {
signature, _ := hex.DecodeString(keySignature.Signature)
pubkey, _ := hex.DecodeString(keySignature.Address.PublicKey)
signaturePubkey := btcTransaction.SignaturePubkey{
Signature: signature,
Pubkey: pubkey,
}
//sigPub = append(sigPub, signaturePubkey)
txHash := btcTransaction.TxHash{
Hash: keySignature.Message,
Normal: &btcTransaction.NormalTx{
Address: keySignature.Address.Address,
SigType: btcTransaction.SigHashAll,
SigPub: signaturePubkey,
},
}
transHash = append(transHash, txHash)
decoder.wm.Log.Debug("Signature:", keySignature.Signature)
decoder.wm.Log.Debug("PublicKey:", keySignature.Address.PublicKey)
}
}
txBytes, err := hex.DecodeString(emptyTrans)
if err != nil {
return errors.New("Invalid transaction hex data!")
}
trx, err := btcTransaction.DecodeRawTransaction(txBytes, decoder.wm.Config.SupportSegWit)
if err != nil {
return errors.New("Invalid transaction data! ")
}
for _, vin := range trx.Vins {
utxo, err := decoder.wm.GetTxOut(vin.GetTxID(), uint64(vin.GetVout()))
if err != nil {
return err
}
txAmount := common.StringNumToBigIntWithExp(utxo.Value, decoder.wm.Decimal())
txUnlock := btcTransaction.TxUnlock{
LockScript: utxo.ScriptPubKey,
SigType: btcTransaction.SigHashAll,
Amount: txAmount.Uint64(),
}
txUnlocks = append(txUnlocks, txUnlock)
}
//decoder.wm.Log.Debug(emptyTrans)
////////填充签名结果到空交易单
// 传入TxUnlock结构体的原因是: 解锁向脚本支付的UTXO时需要对应地址的赎回脚本, 当前案例的对应字段置为 "" 即可
signedTrans, err := btcTransaction.InsertSignatureIntoEmptyTransaction(emptyTrans, transHash, txUnlocks, decoder.wm.Config.SupportSegWit)
if err != nil {
return fmt.Errorf("transaction compose signatures failed")
}
//else {
// // fmt.Println("拼接后的交易单")
// // fmt.Println(signedTrans)
// //}
if decoder.wm.Config.IsTestNet {
addressPrefix = decoder.wm.Config.TestNetAddressPrefix
} else {
addressPrefix = decoder.wm.Config.MainNetAddressPrefix
}
/////////验证交易单
//验证时,对于公钥哈希地址,需要将对应的锁定脚本传入TxUnlock结构体
pass := btcTransaction.VerifyRawTransaction(signedTrans, txUnlocks, decoder.wm.Config.SupportSegWit, addressPrefix)
if pass {
decoder.wm.Log.Debug("transaction verify passed")
rawTx.IsCompleted = true
rawTx.RawHex = signedTrans
} else {
decoder.wm.Log.Debug("transaction verify failed")
rawTx.IsCompleted = false
}
return nil
}
//GetRawTransactionFeeRate 获取交易单的费率
func (decoder *TransactionDecoder) GetRawTransactionFeeRate() (feeRate string, unit string, err error) {
rate, err := decoder.wm.EstimateFeeRate()
if err != nil {
return "", "", err
}
return rate.StringFixed(decoder.wm.Decimal()), "K", nil
}
////////////////////////// omnicore implement //////////////////////////
//CreateOmniRawTransaction 创建Omni交易单
func (decoder *TransactionDecoder) CreateOmniRawTransaction(wrapper openwallet.WalletDAI, rawTx *openwallet.RawTransaction) error {
var (
//vins = make([]omniTransaction.Vin, 0)
//vouts = make([]omniTransaction.Vout, 0)
//txUnlocks = make([]omniTransaction.TxUnlock, 0)
outputAddrs = make(map[string]decimal.Decimal)
omniOutputAddrs = make(map[string]string)
toAddress string
toAmount = decimal.Zero
availableUTXO = make([]*Unspent, 0)
usedUTXO = make([]*Unspent, 0)
totalTokenBalance = decimal.Zero
useTokenBalance = decimal.Zero
useTokenAddress = ""
missUtxoAddress = ""
missToken = make([]string, 0)
balance = decimal.New(0, 0)
actualFees = decimal.New(0, 0)
feesRate = decimal.New(0, 0)
accountID = rawTx.Account.AccountID
//accountTotalSent = decimal.Zero
//txFrom = make([]string, 0)
//txTo = make([]string, 0)
)
if !decoder.wm.Config.OmniSupport {
return fmt.Errorf("%s is not support omnicore transfer", decoder.wm.Symbol())
}
if len(rawTx.Coin.Contract.Address) == 0 {
return fmt.Errorf("contract address is empty")
}
//Omni代币编号
propertyID := common.NewString(rawTx.Coin.Contract.Address).UInt64()
tokenCoin := rawTx.Coin.Contract.Token
tokenDecimals := int32(rawTx.Coin.Contract.Decimals)
//转账最低成本
transferCost, _ := decimal.NewFromString(decoder.wm.Config.OmniTransferCost)
address, err := wrapper.GetAddressList(0, -1, "AccountID", rawTx.Account.AccountID)
if err != nil {
return err
}
if len(address) == 0 {
return fmt.Errorf("[%s] have not addresses", accountID)
}
if len(rawTx.To) == 0 {
return errors.New("Receiver addresses is empty!")
}
//omni限制只能发送目标一个
if len(rawTx.To) > 1 {
return fmt.Errorf("ommni transfer not support multiple receiver address")
}
//选择一个输出地址
for to, amount := range rawTx.To {
toAddress = to
toAmount, _ = decimal.NewFromString(amount)
//计算账户的实际转账amount
//addresses, findErr := wrapper.GetAddressList(0, -1, "AccountID", rawTx.Account.AccountID, "Address", to)
//if findErr != nil || len(addresses) == 0 {
// accountTotalSent = accountTotalSent.Add(toAmount)
//}
}
/*
1. 遍历所有地址,获取token余额。
1)累计所有地址token余额。
2)没有token余额的地址,加入到没有token余额数组,其地址有utxo可用于手续费使用。
3)判断是否可用Token余额超过可发送数量,是则继续遍历。
4)记录最大的可余额,记录可用token余额地址。
5)查询有token余额的地址的utxo,没有utxo,记录缺少utxo地址,记录可用utxo。
2. 遍历所有地址后,全部Token余额不足, 返回错误Token余额不足。
3. 全部Token余额足够,可用余额不足,返回地址的最大Token余额不足。
4. 全部Token余额足够,可用余额足够,地址的没有utxo,返回错误。
5. 先排序可用utxo,再把没有token余额的地址所有utxo查出来,加入到可用utxo数组最后。
6. 最后可用的utxo不足,返回错误主链币不足。
7. 可用token和可用utxo足够,构建交易单。
*/
for _, address := range address {
//查找地址token余额
tokenBalance, checkErr := decoder.wm.GetOmniBalance(propertyID, address.Address)
if checkErr != nil {
return checkErr
}
//合计总token余额
totalTokenBalance = totalTokenBalance.Add(tokenBalance)
//没有余额的地址可以作为手续费使用
if tokenBalance.LessThanOrEqual(decimal.Zero) {
missToken = append(missToken, address.Address)
continue
} else {
//判断是否可用Token余额超过可发送数量,则停止遍历
if useTokenBalance.GreaterThanOrEqual(toAmount) && len(missUtxoAddress) == 0 {
continue
}
//totalTokenBalance = totalTokenBalance.Add(tokenBalance)
//查找账户的utxo
unspents, tokenErr := decoder.wm.ListUnspent(0, address.Address)
if tokenErr != nil {
return tokenErr
}
//取最大余额
//if tokenBalance.GreaterThanOrEqual(toAmount) {
useTokenBalance = tokenBalance
useTokenAddress = address.Address
//}
//记录缺少utxo的地址
if len(unspents) == 0 {
missUtxoAddress = address.Address
//decoder.wm.Log.Debug("missUtxoAddress:", missUtxoAddress)
} else {
missUtxoAddress = ""
}
//else {
//useTokenBalance = tokenBalance
//useTokenBalance = useTokenBalance.Add(tokenBalance)
//}
availableUTXO = unspents
//availableUTXO = append(availableUTXO, unspents...)
}
}
//遍历所有地址后,全部Token余额不足, 返回错误Token余额不足
if totalTokenBalance.LessThan(toAmount) {
return openwallet.Errorf(openwallet.ErrInsufficientTokenBalanceOfAddress, "account[%s] omni[%s] total balance: %s is not enough! ", accountID, tokenCoin, totalTokenBalance.StringFixed(tokenDecimals))
}
//单个地址的可用Token余额不足够
if useTokenBalance.LessThan(toAmount) {
return openwallet.Errorf(openwallet.ErrInsufficientFees, "account[%s] omni[%s] total balance is enough, but the available balance: %s of address[%s] is not enough! ", accountID, tokenCoin, useTokenBalance.StringFixed(tokenDecimals), useTokenAddress)
} else {
//可用Token余额足够,但没有utxo,返回错误及有Token余额的地址没有可用主链币
if len(missUtxoAddress) > 0 {
return openwallet.Errorf(openwallet.ErrInsufficientFees, "account[%s] omni[%s] total balance is enough, but the utxo of address[%s] is empty! ", accountID, tokenCoin, missUtxoAddress)
}
}
//选择一个地址作为发送
//txFrom = []string{fmt.Sprintf("%s:%s", availableUTXO[0].Address, toAmount.StringFixed(tokenDecimals))}
//获取utxo,按小到大排序
sort.Sort(UnspentSort{availableUTXO, func(a, b *Unspent) int {
if a.Amount > b.Amount {
return 1
} else {
return -1
}
}})
//查找账户没有token余额的utxo,可用于手续费
if len(missToken) > 0 {
missTokenUnspents, err := decoder.wm.ListUnspent(0, missToken...)
if err != nil {
return err
}
availableUTXO = append(availableUTXO, missTokenUnspents...)
}
//获取手续费率
if len(rawTx.FeeRate) == 0 {
feesRate, err = decoder.wm.EstimateFeeRate()
if err != nil {
return err
}
} else {
feesRate, _ = decimal.NewFromString(rawTx.FeeRate)
}
decoder.wm.Log.Info("Calculating wallet unspent record to build transaction...")
computeTotalSend := transferCost
//循环的计算余额是否足够支付发送数额+手续费
for {
usedUTXO = make([]*Unspent, 0)
balance = decimal.Zero
//计算一个可用于支付的余额
for _, u := range availableUTXO {
if u.Spendable {
ua, _ := decimal.NewFromString(u.Amount)
balance = balance.Add(ua)
usedUTXO = append(usedUTXO, u)
if balance.GreaterThanOrEqual(computeTotalSend) {
break
}
}
}
if balance.LessThan(computeTotalSend) {
return openwallet.Errorf(openwallet.ErrInsufficientFees, "The [%s] available utxo balance: %s is not enough! ", decoder.wm.Symbol(), balance.StringFixed(decoder.wm.Decimal()))
}
//计算手续费,输出地址有2个,一个是发送,一个是找零,一个是op_reture
fees, err := decoder.wm.EstimateFee(int64(len(usedUTXO)), int64(3), feesRate)
if err != nil {
return err
}
//如果要手续费有发送支付,得计算加入手续费后,计算余额是否足够
//总共要发送的
computeTotalSend = transferCost.Add(fees)
if computeTotalSend.GreaterThan(balance) {
continue
}
computeTotalSend = transferCost
actualFees = fees
break
}
//UTXO如果大于设定限制,则分拆成多笔交易单发送
if len(usedUTXO) > decoder.wm.Config.MaxTxInputs {
errStr := fmt.Sprintf("The transaction is use max inputs over: %d", decoder.wm.Config.MaxTxInputs)
return errors.New(errStr)
}
//取账户最后一个地址
changeAddress := usedUTXO[0].Address
changeAmount := balance.Sub(computeTotalSend).Sub(actualFees)
rawTx.FeeRate = feesRate.StringFixed(decoder.wm.Decimal())
rawTx.Fees = actualFees.StringFixed(decoder.wm.Decimal())
decoder.wm.Log.Std.Notice("-----------------------------------------------")
decoder.wm.Log.Std.Notice("From Account: %s", accountID)
decoder.wm.Log.Std.Notice("To Address: %s", toAddress)
decoder.wm.Log.Std.Notice("Amount %s: %v", tokenCoin, toAmount.StringFixed(tokenDecimals))
decoder.wm.Log.Std.Notice("Use %s: %v", decoder.wm.Symbol(), balance.StringFixed(decoder.wm.Decimal()))
decoder.wm.Log.Std.Notice("Fees %s: %v", decoder.wm.Symbol(), actualFees.StringFixed(decoder.wm.Decimal()))
decoder.wm.Log.Std.Notice("Receive %s: %v", decoder.wm.Symbol(), computeTotalSend.StringFixed(decoder.wm.Decimal()))
decoder.wm.Log.Std.Notice("Change %s: %v", decoder.wm.Symbol(), changeAmount.StringFixed(decoder.wm.Decimal()))
decoder.wm.Log.Std.Notice("Change Address: %v", changeAddress)
decoder.wm.Log.Std.Notice("-----------------------------------------------")
outputAddrs = appendOutput(outputAddrs, toAddress, computeTotalSend)
//outputAddrs[toAddress] = computeTotalSend.StringFixed(decoder.wm.Decimal())
//changeAmount := balance.Sub(totalSend).Sub(actualFees)
if changeAmount.GreaterThan(decimal.Zero) {
outputAddrs = appendOutput(outputAddrs, changeAddress, changeAmount)
//outputAddrs[changeAddress] = changeAmount.StringFixed(decoder.wm.Decimal())
}
omniOutputAddrs[toAddress] = toAmount.StringFixed(tokenDecimals)
err = decoder.createOmniRawTransaction(wrapper, rawTx, usedUTXO, outputAddrs, omniOutputAddrs)
if err != nil {
return err
}
return nil
}
//SignOmniRawTransaction 签名交易单
func (decoder *TransactionDecoder) SignOmniRawTransaction(wrapper openwallet.WalletDAI, rawTx *openwallet.RawTransaction) error {
if rawTx.Signatures == nil || len(rawTx.Signatures) == 0 {
//this.wm.Log.Std.Error("len of signatures error. ")
return fmt.Errorf("transaction signature is empty")
}
key, err := wrapper.HDKey()
if err != nil {
return err
}
//keySignatures := rawTx.Signatures[rawTx.Account.AccountID]
for accountID, keySignatures := range rawTx.Signatures {
decoder.wm.Log.Debug("accountID:", accountID)
if keySignatures != nil {
for _, keySignature := range keySignatures {
childKey, err := key.DerivedKeyWithPath(keySignature.Address.HDPath, keySignature.EccType)
keyBytes, err := childKey.GetPrivateKeyBytes()
if err != nil {
return err
}
decoder.wm.Log.Debug("privateKey:", hex.EncodeToString(keyBytes))
//privateKeys = append(privateKeys, keyBytes)
txHash := omniTransaction.TxHash{
Hash: keySignature.Message,
Normal: &omniTransaction.NormalTx{
Address: keySignature.Address.Address,
SigType: btcTransaction.SigHashAll,
},
}
//transHash = append(transHash, txHash)
decoder.wm.Log.Debug("hash:", txHash.GetTxHashHex())
//签名交易
/////////交易单哈希签名
sigPub, err := omniTransaction.SignRawTransactionHash(txHash.GetTxHashHex(), keyBytes)
if err != nil {
return fmt.Errorf("transaction hash sign failed, unexpected error: %v", err)
} else {
//for i, s := range sigPub {
// decoder.wm.Log.Info("第", i+1, "个签名结果")
// decoder.wm.Log.Info()
// decoder.wm.Log.Info("对应的公钥为")
// decoder.wm.Log.Info(hex.EncodeToString(s.Pubkey))
//}
//txHash.Normal.SigPub = *sigPub
}
keySignature.Signature = hex.EncodeToString(sigPub.Signature)
}
}
rawTx.Signatures[accountID] = keySignatures
}
decoder.wm.Log.Info("transaction hash sign success")
//decoder.wm.Log.Info("rawTx.Signatures 1:", rawTx.Signatures)
return nil
}
//VerifyOmniRawTransaction 验证交易单,验证交易单并返回加入签名后的交易单
func (decoder *TransactionDecoder) VerifyOmniRawTransaction(wrapper openwallet.WalletDAI, rawTx *openwallet.RawTransaction) error {
//先加载是否有配置文件
//err := decoder.wm.LoadConfig()
//if err != nil {
// return err
//}
var (
txUnlocks = make([]omniTransaction.TxUnlock, 0)
emptyTrans = rawTx.RawHex
//sigPub = make([]btcTransaction.SignaturePubkey, 0)
transHash = make([]omniTransaction.TxHash, 0)
addressPrefix omniTransaction.AddressPrefix
)
if rawTx.Signatures == nil || len(rawTx.Signatures) == 0 {
//this.wm.Log.Std.Error("len of signatures error. ")
return fmt.Errorf("transaction signature is empty")
}
for accountID, keySignatures := range rawTx.Signatures {
decoder.wm.Log.Debug("accountID Signatures:", accountID)
for _, keySignature := range keySignatures {
signature, _ := hex.DecodeString(keySignature.Signature)
pubkey, _ := hex.DecodeString(keySignature.Address.PublicKey)
signaturePubkey := omniTransaction.SignaturePubkey{
Signature: signature,
Pubkey: pubkey,
}
//sigPub = append(sigPub, signaturePubkey)
txHash := omniTransaction.TxHash{
Hash: keySignature.Message,
Normal: &omniTransaction.NormalTx{
Address: keySignature.Address.Address,
SigType: btcTransaction.SigHashAll,
SigPub: signaturePubkey,
},
}
transHash = append(transHash, txHash)
decoder.wm.Log.Debug("Signature:", keySignature.Signature)
decoder.wm.Log.Debug("PublicKey:", keySignature.Address.PublicKey)
}
}
txBytes, err := hex.DecodeString(emptyTrans)
if err != nil {
return errors.New("Invalid transaction hex data!")
}
trx, err := omniTransaction.DecodeRawTransaction(txBytes, decoder.wm.Config.SupportSegWit)
if err != nil {
return errors.New("Invalid transaction data! ")
}
for i, vin := range trx.Vins {
utxo, err := decoder.wm.GetTxOut(vin.GetTxID(), uint64(vin.GetVout()))
if err != nil {
return err
}
txUnlock := omniTransaction.TxUnlock{
LockScript: utxo.ScriptPubKey,
SigType: btcTransaction.SigHashAll}
txUnlocks = append(txUnlocks, txUnlock)
transHash = resetTransHashFunc(transHash, utxo.Addr, i)
}
//decoder.wm.Log.Debug(emptyTrans)
if decoder.wm.Config.IsTestNet {
addressPrefix = omniTransaction.AddressPrefix{
P2PKHPrefix: decoder.wm.Config.TestNetAddressPrefix.P2PKHPrefix,
P2WPKHPrefix: decoder.wm.Config.TestNetAddressPrefix.P2WPKHPrefix,
Bech32Prefix: decoder.wm.Config.TestNetAddressPrefix.Bech32Prefix,
}
} else {
addressPrefix = omniTransaction.AddressPrefix{
P2PKHPrefix: decoder.wm.Config.MainNetAddressPrefix.P2PKHPrefix,
P2WPKHPrefix: decoder.wm.Config.MainNetAddressPrefix.P2WPKHPrefix,
Bech32Prefix: decoder.wm.Config.MainNetAddressPrefix.Bech32Prefix,
}
}
////////填充签名结果到空交易单
// 传入TxUnlock结构体的原因是: 解锁向脚本支付的UTXO时需要对应地址的赎回脚本, 当前案例的对应字段置为 "" 即可
signedTrans, err := omniTransaction.InsertSignatureIntoEmptyTransaction(emptyTrans, transHash, txUnlocks)
if err != nil {
return fmt.Errorf("transaction compose signatures failed")
}
//else {
// // fmt.Println("拼接后的交易单")
// // fmt.Println(signedTrans)
// //}
/////////验证交易单
//验证时,对于公钥哈希地址,需要将对应的锁定脚本传入TxUnlock结构体
pass := omniTransaction.VerifyRawTransaction(signedTrans, txUnlocks, addressPrefix)
if pass {
decoder.wm.Log.Debug("transaction verify passed")
rawTx.IsCompleted = true
rawTx.RawHex = signedTrans
} else {
decoder.wm.Log.Debug("transaction verify failed")
rawTx.IsCompleted = false
decoder.wm.Log.Warningf("[Sid: %s] signedTrans: %s", rawTx.Sid, signedTrans)
decoder.wm.Log.Warningf("[Sid: %s] txUnlocks: %+v", rawTx.Sid, txUnlocks)
decoder.wm.Log.Warningf("[Sid: %s] addressPrefix: %+v", rawTx.Sid, addressPrefix)
}
return nil
}
//CreateBTCSummaryRawTransaction 创建BTC汇总交易
func (decoder *TransactionDecoder) CreateBTCSummaryRawTransaction(wrapper openwallet.WalletDAI, sumRawTx *openwallet.SummaryRawTransaction) ([]*openwallet.RawTransactionWithError, error) {
var (
feesRate = decimal.New(0, 0)
accountID = sumRawTx.Account.AccountID
minTransfer, _ = decimal.NewFromString(sumRawTx.MinTransfer)
//retainedBalance, _ = decimal.NewFromString(sumRawTx.RetainedBalance)
sumAddresses = make([]string, 0)
rawTxArray = make([]*openwallet.RawTransactionWithError, 0)
sumUnspents []*Unspent
outputAddrs map[string]decimal.Decimal
totalInputAmount decimal.Decimal
)
//if minTransfer.LessThan(retainedBalance) {
// return nil, fmt.Errorf("mini transfer amount must be greater than address retained balance")