-
Notifications
You must be signed in to change notification settings - Fork 20
/
TransactionUtil.java
1863 lines (1706 loc) · 75.5 KB
/
TransactionUtil.java
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 cn.chain33.javasdk.utils;
import cn.chain33.javasdk.model.Address;
import cn.chain33.javasdk.model.Signature;
import cn.chain33.javasdk.model.Transaction;
import cn.chain33.javasdk.model.TransferBalanceRequest;
import cn.chain33.javasdk.model.decode.DecodeRawTransaction;
import cn.chain33.javasdk.model.enums.AddressType;
import cn.chain33.javasdk.model.enums.ChainID;
import cn.chain33.javasdk.model.enums.SignType;
import cn.chain33.javasdk.model.gm.SM2KeyPair;
import cn.chain33.javasdk.model.gm.SM2Util;
import cn.chain33.javasdk.model.protobuf.*;
import cn.chain33.javasdk.model.protobuf.ExecuterProtobuf.ModifyConfig.Builder;
import cn.chain33.javasdk.model.protobuf.ManageProtobuf.ManageAction;
import cn.chain33.javasdk.model.protobuf.TokenActionProtoBuf.TokenAction;
import cn.chain33.javasdk.model.protobuf.TokenActionProtoBuf.TokenFinishCreate;
import cn.chain33.javasdk.model.protobuf.TokenActionProtoBuf.TokenPreCreate;
import cn.chain33.javasdk.model.protobuf.TransactionAllProtobuf.AssetsTransfer;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import net.vrallev.java.ecc.Ecc25519Helper;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.utils.Numeric;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* @author logan 2018年5月14日
*/
public class TransactionUtil {
public static final long DEFAULT_FEE = 1000000;
public static final long PARA_CREATE_EVM_FEE = 3000000;
public static final long PARA_CALL_EVM_FEE = 200000;
private static final SignType DEFAULT_SIGNTYPE = SignType.SECP256K1;
private final static Long TX_HEIGHT_OFFSET = 1L << 62;
private final static Long LowAllowPackHeight = 30L;
private static final long DURATION = 1;
private static final long MICROSECOND = DURATION * 1000;
private static final long MILLISECOND = MICROSECOND * 1000;
private static final long SECOND = MILLISECOND * 1000;
private static final long EXPIREBOUND = 1000000000;
private static final long MAXTXSIZE = 100000;
private static byte[] addrSeed = "address seed bytes for public key".getBytes();
/**
* @param expire 单位为秒
* @return
* @description expire转换为纳秒为单位
*/
public static long getExpire(long expire) {
expire = expire * EXPIREBOUND;
if (expire > EXPIREBOUND) {
if (expire < SECOND * 120) {
expire = SECOND * 120;
}
expire = System.currentTimeMillis() / 1000 + expire / SECOND;
return expire;
} else {
return expire;
}
}
/**
* byte数组合并
*
* @param byte_1
* @param byte_2
* @return
*/
public static byte[] byteMerger(byte[] byte_1, byte[] byte_2) {
byte[] byte_3 = new byte[byte_1.length + byte_2.length];
System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
return byte_3;
}
/**
* @param pubKey 公钥
* @return 地址
* @description 通过公钥生成地址
*/
public static String genAddress(byte[] pubKey) {
byte[] sha256 = TransactionUtil.Sha256(pubKey);
byte[] ripemd160 = TransactionUtil.ripemd160(sha256);
Address address = new Address();
address.setHash160(ripemd160);
return addressToString(address);
}
/**
* @param pubKey 公钥
* @return 地址
* @description 通过公钥生成YCC格式地址(以太坊形式,以0x开头的地址)
*/
public static String genAddressForYCC(BigInteger pubKey) {
//通过公钥生成钱包地址
String address = Keys.getAddress(pubKey);
return "0x" + address;
}
/**
* @param privateKey 私钥
* @param addressType 0表示生成btc格式地址,2表示生成eth格式地址
* @return 地址
* @description 通过私钥生成地址
*/
public static String genAddress(String privateKey, AddressType addressType) {
switch (addressType) {
case BTC_ADDRESS: {
return genAddress(HexUtil.fromHexString(getHexPubKeyFromPrivKey(privateKey)));
}
case ETH_ADDRESS: {
return genAddressForYCC(getHexPubKeyFromPrivKeyForYCC(privateKey));
}
default:
return null;
}
}
/**
* 将evm地址转成base58编码地址
*
* @param addressByte
* @return
* @throws Exception
*/
public static String encodeAddress(byte[] addressByte) {
Address address = new Address();
address.setHash160(addressByte);
return addressToString(address);
}
/**
* 将ETH地址转成BTC地址
*
* @param ethAddress eth格式地址
* @return
*/
public static String convertETHToBTC(String ethAddress) {
return encodeAddress(HexUtil.fromHexString(ethAddress));
}
/**
* 将BTC地址转为ETH地址
*
* @param btcAddress BTC格式地址
* @return
*/
public static String convertBTCToETH(String btcAddress) {
try {
return "0x" + HexUtil.toHexString(decodeAddress(btcAddress));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将base58编码的地址转成evm地址
*
* @param address chain33地址
* @return
* @throws Exception
*/
public static byte[] decodeAddress(String address) throws Exception {
byte[] decodeBytes = Base58Util.decode(address);
if (decodeBytes.length < 25) {
throw new Exception("Address too short " + HexUtil.toHexString(decodeBytes));
}
if (!validAddress(address)) {
throw new Exception("Address check failed " + HexUtil.toHexString(decodeBytes));
}
return ByteUtils.subArray(decodeBytes, 1, decodeBytes.length - 4);
}
/**
* @param address 地址
* @return 校验结果
* @description 校验地址是否符合规则
*/
public static boolean validAddress(String address) {
try {
byte[] decodeBytes = Base58Util.decode(address);
byte[] checkByteByte = ByteUtils.subArray(decodeBytes, decodeBytes.length - 4);
byte[] noCheckByte = ByteUtils.subArray(decodeBytes, 0, decodeBytes.length - 4);
byte[] sha256 = Sha256(noCheckByte);
byte[] twice = Sha256(sha256);
for (int i = 0; i < 4; i++) {
if (twice[i] != checkByteByte[i]) {
return false;
}
}
return true;
} catch (Exception e) {
return false;
}
}
/**
* @param address 地址
* @return 校验结果
* @description 校验普通个人地址是否符合以太坊地址规则
*/
public static boolean validETHAddress(String address) {
if (!address.startsWith("0x"))
return false;
String cleanHexInput = Numeric.cleanHexPrefix(address);
try {
Numeric.toBigIntNoPrefix(cleanHexInput);
} catch (NumberFormatException e) {
return false;
}
return cleanHexInput.length() == 40;
}
/**
* @param address 地址
* @return 校验结果
* @description 校验地址是否符合规则
*/
public static boolean validAddress(String address, AddressType addressType) {
switch (addressType) {
case BTC_ADDRESS: {
return validAddress(address);
}
case ETH_ADDRESS: {
return validETHAddress(address);
}
default:
return false;
}
}
/**
* @param byteArr
* @param start
* @param end
* @return
* @description byte数组截取
*/
public static byte[] subByteArr(byte[] byteArr, Integer start, Integer end) {
Integer diff = end - start;
byte[] byteTarget = new byte[diff];
if (diff > byteArr.length) {
diff = byteArr.length;
}
for (int i = 0; i < diff; i++) {
byteTarget[i] = byteArr[i];
}
return byteTarget;
}
public static byte[] Sha256(byte[] sourceByte) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(sourceByte);
byte byteData[] = md.digest();
return byteData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Long getRandomNonce() {
Random random = new Random(System.nanoTime());
return Math.abs(random.nextLong());
}
/**
* @param to 目标地址
* @param amount 数量
* @param coinToken 主代币则为""
* @param note 备注,没有为""
* @return payload
* @description 本地创建coins转账payload
*/
public static byte[] createTransferPayLoad(String to, Long amount, String coinToken, String note) {
TransactionAllProtobuf.AssetsTransfer.Builder assetsTransferBuilder = TransactionAllProtobuf.AssetsTransfer.newBuilder();
assetsTransferBuilder.setCointoken(coinToken);
assetsTransferBuilder.setAmount(amount);
try {
assetsTransferBuilder.setNote(ByteString.copyFrom(note, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
assetsTransferBuilder.setTo(to);
AssetsTransfer assetsTransfer = assetsTransferBuilder.build();
CoinsProtobuf.CoinsAction.Builder coinsActionBuilder = CoinsProtobuf.CoinsAction.newBuilder();
coinsActionBuilder.setTy(1);
coinsActionBuilder.setTransfer(assetsTransfer);
CoinsProtobuf.CoinsAction coinsAction = coinsActionBuilder.build();
byte[] payload = coinsAction.toByteArray();
return payload;
}
/**
* @param privateKey
* @param toAddress
* @param execer
* @param payLoad
* @return
* @description 本地创建转账交易
*/
public static String createTransferTx(String privateKey, String toAddress, String execer, byte[] payLoad) {
byte[] privateKeyBytes = HexUtil.fromHexString(privateKey);
return createTxMain(privateKeyBytes, toAddress, execer.getBytes(), payLoad, DEFAULT_SIGNTYPE, DEFAULT_FEE);
}
public static String createTransferTxForYCC(String privateKey, String toAddress, String execer, byte[] payLoad) {
byte[] privateKeyBytes = HexUtil.fromHexString(privateKey);
return createTxMain(privateKeyBytes, toAddress, execer.getBytes(), payLoad, SignType.ETH_SECP256K1, ChainID.YCC.getID(), DEFAULT_FEE);
}
public static String createTransferTx(String privateKey, String toAddress, String execer, byte[] payLoad, long fee) {
byte[] privateKeyBytes = HexUtil.fromHexString(privateKey);
return createTxMain(privateKeyBytes, toAddress, execer.getBytes(), payLoad, DEFAULT_SIGNTYPE, fee);
}
public static String createTransferTx(String privateKey, String toAddress, String execer, byte[] payLoad, long fee, long txheight) {
byte[] privateKeyBytes = HexUtil.fromHexString(privateKey);
return createTxMain(privateKeyBytes, toAddress, execer.getBytes(), payLoad, DEFAULT_SIGNTYPE, fee, txheight);
}
public static TransactionAllProtobuf.Transaction createTransferTx2(String privateKey, String toAddress, String execer, byte[] payLoad, long fee, long txheight) {
byte[] privateKeyBytes = HexUtil.fromHexString(privateKey);
return createTxMain2(privateKeyBytes, toAddress, execer.getBytes(), payLoad, DEFAULT_SIGNTYPE, fee, txheight);
}
public static String createTx(String privateKey, String execer, String payLoad) {
byte[] privateKeyBytes = HexUtil.fromHexString(privateKey);
return createTx(privateKeyBytes, execer.getBytes(), payLoad.getBytes(), DEFAULT_SIGNTYPE, DEFAULT_FEE);
}
/**
* 构建普通BTY签名交易
*
* @param privateKey
* @param execer
* @param payLoad
* @param fee
* @return
*/
public static String createTx(String privateKey, String execer, String payLoad, long fee) {
byte[] privateKeyBytes = HexUtil.fromHexString(privateKey);
return createTx(privateKeyBytes, execer.getBytes(), payLoad.getBytes(), DEFAULT_SIGNTYPE, fee);
}
/**
* 构建YCC平行链签名交易
*
* @param privateKey
* @param execer
* @param payLoad
* @param fee
* @return
*/
public static String createTxParaForYCC(String privateKey, String execer, byte[] payLoad, long fee) {
byte[] privateKeyBytes = HexUtil.fromHexString(privateKey);
return createTxPara(privateKeyBytes, execer.getBytes(), payLoad, SignType.ETH_SECP256K1, ChainID.YCC.getID(), AddressType.ETH_ADDRESS, fee);
}
/**
* 构建YCC主链签名交易
*
* @param privateKey
* @param toAddress
* @param execer
* @param payLoad
* @param fee
* @return
*/
public static String createTxMainForYCC(String privateKey, String toAddress, String execer, byte[] payLoad, long fee) {
byte[] privateKeyBytes = HexUtil.fromHexString(privateKey);
return createTxMain(privateKeyBytes, toAddress, execer.getBytes(), payLoad, SignType.ETH_SECP256K1, ChainID.YCC.getID(), fee);
}
public static String createTx(byte[] privateKey, byte[] execer, byte[] payLoad, SignType signType, long fee) {
String toAddress = getToAddress(execer);
return createTxMain(privateKey, toAddress, execer, payLoad, signType, fee);
}
/**
* 通用的构建平行链签名交易方法
*
* @param privateKey
* @param execer
* @param payLoad
* @param signType
* @param chainID
* @param fee
* @return
*/
public static String createTxPara(byte[] privateKey, byte[] execer, byte[] payLoad, SignType signType, int chainID, AddressType addressType, long fee) {
String toAddress = getToAddress(execer, addressType);
return createTxMain(privateKey, toAddress, execer, payLoad, signType, chainID, fee);
}
private static String createTxMain(byte[] privateKey, String toAddress, byte[] execer, byte[] payLoad,
SignType signType, long fee) {
if (signType == null)
signType = DEFAULT_SIGNTYPE;
// 如果没有私钥,创建私钥 privateKey =
if (privateKey == null) {
TransactionUtil.generatorPrivateKey();
}
Transaction transaction = createTxRaw(toAddress, execer, payLoad, fee);
// 签名
byte[] protobufData = encodeProtobuf(transaction);
sign(signType, protobufData, privateKey, null, transaction);
// 序列化
byte[] encodeProtobufWithSign = encodeProtobufWithSign(transaction);
String transationStr = HexUtil.toHexString(encodeProtobufWithSign);
return transationStr;
}
/**
* 构建主链交易
*
* @param privateKey 私钥
* @param toAddress 目的地址
* @param execer 执行器名称
* @param payLoad 内容
* @param signType 签名类型
* @param chainID 链ID
* @param fee 手续费
* @return 本地构造的交易
*/
private static String createTxMain(byte[] privateKey, String toAddress, byte[] execer, byte[] payLoad,
SignType signType, int chainID, long fee) {
if (signType == null)
signType = DEFAULT_SIGNTYPE;
// 如果没有私钥,创建私钥 privateKey =
if (privateKey == null) {
TransactionUtil.generatorPrivateKey();
}
Transaction transaction = createTxRaw(toAddress, execer, payLoad, fee, chainID);
// 签名
byte[] protobufData = encodeProtobuf(transaction);
sign(signType, protobufData, privateKey, null, transaction);
// 序列化
byte[] encodeProtobufWithSign = encodeProtobufWithSign(transaction);
String transationStr = HexUtil.toHexString(encodeProtobufWithSign);
return transationStr;
}
/**
* 创建YCC主链交易
*
* @param privateKey 私钥
* @param toAddress 目的地址
* @param execer 执行器名称
* @param payLoad 内容
* @param signType 签名类型
* @param fee 手续费
* @return 本地构造的交易
*/
private static String createTxMainForYCC(byte[] privateKey, String toAddress, byte[] execer, byte[] payLoad,
SignType signType, long fee) {
if (signType == null)
signType = DEFAULT_SIGNTYPE;
// 如果没有私钥,创建私钥 privateKey =
if (privateKey == null) {
TransactionUtil.generatorPrivateKey();
}
Transaction transaction = createTxRaw(toAddress, execer, payLoad, fee, ChainID.YCC.getID());
// 签名
byte[] protobufData = encodeProtobuf(transaction);
sign(signType, protobufData, privateKey, null, transaction);
// 序列化
byte[] encodeProtobufWithSign = encodeProtobufWithSign(transaction);
String transationStr = HexUtil.toHexString(encodeProtobufWithSign);
return transationStr;
}
/**
* @param privateKey 私钥
* @param toAddress 目标地址
* @param execer 例如user.p.xxchain.token
* @param payLoad 内容
* @param signType 签名方式,默认SignType.SECP256K1
* @param fee 手续费
* @param txHeight 联盟链需要,其他为null
* @return
* @description 本地构造交易
*/
public static String createTxMain(byte[] privateKey, String toAddress, byte[] execer, byte[] payLoad,
SignType signType, long fee, Long txHeight) {
if (signType == null)
signType = DEFAULT_SIGNTYPE;
// 如果没有私钥,创建私钥 privateKey =
if (privateKey == null) {
TransactionUtil.generatorPrivateKey();
}
Transaction transation = createTxRaw(toAddress, execer, payLoad, fee);
if (txHeight != null) {
transation.setExpire(txHeight + TX_HEIGHT_OFFSET + LowAllowPackHeight);
}
// 签名
byte[] protobufData = encodeProtobuf(transation);
sign(signType, protobufData, privateKey, null, transation);
// 序列化
byte[] encodeProtobufWithSign = encodeProtobufWithSign(transation);
String transationHash = HexUtil.toHexString(encodeProtobufWithSign);
return transationHash;
}
/**
* @param privateKey 私钥
* @param toAddress 目标地址
* @param execer 例如user.p.xxchain.token
* @param payLoad 内容
* @param signType 签名方式,默认SignType.SECP256K1
* @param fee 手续费
* @param txHeight 联盟链需要,其他为null
* @return
* @description 本地构造交易
*/
public static TransactionAllProtobuf.Transaction createTxMain2(byte[] privateKey, String toAddress, byte[] execer, byte[] payLoad,
SignType signType, long fee, Long txHeight) {
if (signType == null)
signType = DEFAULT_SIGNTYPE;
// 如果没有私钥,创建私钥 privateKey =
if (privateKey == null) {
TransactionUtil.generatorPrivateKey();
}
Transaction transation = createTxRaw(toAddress, execer, payLoad, fee);
if (txHeight != null) {
transation.setExpire(txHeight + TX_HEIGHT_OFFSET + LowAllowPackHeight);
}
// 签名
byte[] protobufData = encodeProtobuf(transation);
sign(signType, protobufData, privateKey, null, transation);
TransactionAllProtobuf.Transaction tx = encodeProtobufWithSign2(transation);
return tx;
}
public static String createTxWithCert(String privateKey, String execer, byte[] payLoad, SignType signType, byte[] cert, byte[] uid) {
if (signType == null)
signType = DEFAULT_SIGNTYPE;
// 如果没有私钥,创建私钥 privateKey =
if (privateKey == null) {
TransactionUtil.generatorPrivateKey();
}
String toAddress = getToAddress(execer.getBytes());
Transaction transation = createTxRaw(toAddress, execer.getBytes(), payLoad, DEFAULT_FEE);
// 签名
byte[] protobufData = encodeProtobuf(transation);
sign(signType, protobufData, HexUtil.fromHexString(privateKey), uid, transation);
byte[] certSign = CertUtils.EncodeCertToSignature(transation.getSignature().getSignature(), cert, uid);
transation.getSignature().setSignature(certSign);
// 序列化
byte[] encodeProtobufWithSign = encodeProtobufWithSign(transation);
String transationHash = HexUtil.toHexString(encodeProtobufWithSign);
return transationHash;
}
public static TransactionAllProtobuf.Transaction createTxWithCertProto(String privateKey, String execer, byte[] payLoad, SignType signType, byte[] cert, byte[] uid) {
if (signType == null)
signType = DEFAULT_SIGNTYPE;
// 如果没有私钥,创建私钥 privateKey =
if (privateKey == null) {
TransactionUtil.generatorPrivateKey();
}
String toAddress = getToAddress(execer.getBytes());
Transaction transation = createTxRaw(toAddress, execer.getBytes(), payLoad, DEFAULT_FEE);
// 签名
byte[] protobufData = encodeProtobuf(transation);
sign(signType, protobufData, HexUtil.fromHexString(privateKey), uid, transation);
byte[] certSign = CertUtils.EncodeCertToSignature(transation.getSignature().getSignature(), cert, uid);
transation.getSignature().setSignature(certSign);
TransactionAllProtobuf.Transaction tx = encodeProtobufWithSign2(transation);
return tx;
}
public static Transaction createTxRaw(String toAddress, byte[] execer, byte[] payLoad, long fee) {
Transaction transation = new Transaction();
transation.setExecer(execer);
transation.setPayload(payLoad);
transation.setFee(fee);
transation.setNonce(TransactionUtil.getRandomNonce());
// 计算To
transation.setTo(toAddress);
return transation;
}
/**
* 构建通用的未签名交易
*
* @param toAddress
* @param execer
* @param payLoad
* @param fee
* @param chainID
* @return
*/
public static Transaction createTxRaw(String toAddress, byte[] execer, byte[] payLoad, long fee, int chainID) {
Transaction transation = new Transaction();
transation.setExecer(execer);
transation.setPayload(payLoad);
transation.setFee(fee);
transation.setNonce(TransactionUtil.getRandomNonce());
transation.setChainID(chainID);
// 计算To
transation.setTo(toAddress);
return transation;
}
/**
* 构造转帐交易,并签名
*
* @return 交易hash
*/
public static String transferBalanceMain(TransferBalanceRequest transferBalanceRequest) {
String to = transferBalanceRequest.getTo();
Long amount = transferBalanceRequest.getAmount();
String coinToken = transferBalanceRequest.getCoinToken();
String note = transferBalanceRequest.getNote();
SignType signType = transferBalanceRequest.getSignType();
String privateKey = transferBalanceRequest.getFromPrivateKey();
String execer = transferBalanceRequest.getExecer();
int chainID = transferBalanceRequest.getChainID();
long fee = transferBalanceRequest.getFee();
byte[] payload = createTransferPayLoad(to, amount, coinToken, note);
byte[] execerBytes;
if (StringUtil.isNotEmpty(execer)) {
execerBytes = execer.getBytes();
} else {
execerBytes = "none".getBytes();
}
byte[] privateKeyBytes = HexUtil.fromHexString(privateKey);
String transferTx = createTxMain(privateKeyBytes, to, execerBytes, payload, signType, chainID, fee);
return transferTx;
}
/**
* 计算to
*
* @param execer
* @return
*/
public static String getToAddress(byte[] execer) {
byte[] mergeredByte = TransactionUtil.byteMerger(addrSeed, execer);
byte[] sha256_1 = TransactionUtil.Sha256(mergeredByte);
for (int i = 0; i < sha256_1.length; i++) {
sha256_1[i] = (byte) (sha256_1[i] & 0xff);
}
byte[] sha256_2 = TransactionUtil.Sha256(sha256_1);
byte[] sha256_3 = TransactionUtil.Sha256(sha256_2);
byte[] ripemd160 = TransactionUtil.ripemd160(sha256_3);
Address address = new Address();
address.setHash160(ripemd160);
return addressToString(address);
}
/**
* 通用根据执行器名称获取相应地址格式执行器地址
*
* @param execer
* @param addressType
* @return
*/
public static String getToAddress(byte[] execer, AddressType addressType) {
byte[] mergeredByte = TransactionUtil.byteMerger(addrSeed, execer);
//两次sha256处理
byte[] sha256_1 = TransactionUtil.Sha256(mergeredByte);
byte[] sha256_2 = TransactionUtil.Sha256(sha256_1);
if (addressType == AddressType.BTC_ADDRESS) {
byte[] sha256_3 = TransactionUtil.Sha256(sha256_2);
byte[] ripemd160 = TransactionUtil.ripemd160(sha256_3);
Address address = new Address();
address.setHash160(ripemd160);
return addressToString(address);
}
if (addressType == AddressType.ETH_ADDRESS) {
//根据公钥生成eth格式地址,因为根据执行器名称生成的公钥不具有压缩属性,所以需要Keccak256生成相应的地址
byte[] srcBytes = new byte[sha256_2.length - 1];
System.arraycopy(sha256_2, 1, srcBytes, 0, sha256_2.length - 1);
byte[] bytes = Keccak256Util.keccak256(srcBytes);
//取后20位作为地址
byte[] data = new byte[20];
System.arraycopy(bytes, 12, data, 0, 20);
return "0x" + HexUtil.toHexString(data);
}
return null;
}
/**
* @return 私钥
* @description 创建私钥和公钥
*/
public static byte[] generatorPrivateKey() {
int length = 0;
byte[] privateKey;
do {
ECKeyPairGenerator gen = new ECKeyPairGenerator();
SecureRandom secureRandom = new SecureRandom();
X9ECParameters secnamecurves = SECNamedCurves.getByName("secp256k1");
ECDomainParameters ecParams = new ECDomainParameters(secnamecurves.getCurve(), secnamecurves.getG(),
secnamecurves.getN(), secnamecurves.getH());
ECKeyGenerationParameters keyGenParam = new ECKeyGenerationParameters(ecParams, secureRandom);
gen.init(keyGenParam);
AsymmetricCipherKeyPair kp = gen.generateKeyPair();
ECPrivateKeyParameters privatekey = (ECPrivateKeyParameters) kp.getPrivate();
privateKey = privatekey.getD().toByteArray();
length = privatekey.getD().toByteArray().length;
} while (length != 32);
return privateKey;
}
/**
* @return 私钥
* @description 生成私钥
*/
public static String generatorPrivateKeyString() {
byte[] generatorPrivateKey = generatorPrivateKey();
ECKey eckey = ECKey.fromPrivate(generatorPrivateKey);
return eckey.getPrivateKeyAsHex();
}
/**
* @param privateKey 私钥
* @return 公钥
* @description 通过私钥生成公钥
*/
public static String getHexPubKeyFromPrivKey(String privateKey) {
ECKey eckey = ECKey.fromPrivate(HexUtil.fromHexString(privateKey));
byte[] pubKey = eckey.getPubKey();
String pubKeyStr = HexUtil.toHexString(pubKey);
return pubKeyStr;
}
/**
* 通过私钥生成YCC格式公钥
*
* @param privateKey
* @return
*/
public static BigInteger getHexPubKeyFromPrivKeyForYCC(String privateKey) {
ECKeyPair keyPair = ECKeyPair.create(HexUtil.fromHexString(privateKey));
BigInteger pubKeyStr = keyPair.getPublicKey();
return pubKeyStr;
}
/**
* 构造交易
*
* @param transaction
* @return
*/
public static byte[] encodeProtobuf(Transaction transaction) {
TransactionAllProtobuf.Transaction.Builder builder = TransactionAllProtobuf.Transaction.newBuilder();
builder.setExecer(ByteString.copyFrom(transaction.getExecer()));
builder.setExpire(transaction.getExpire());
builder.setFee(transaction.getFee());
builder.setNonce(transaction.getNonce());
builder.setPayload(ByteString.copyFrom(transaction.getPayload()));
builder.setTo(transaction.getTo());
builder.setChainID(transaction.getChainID());
TransactionAllProtobuf.Transaction build = builder.build();
byte[] byteArray = build.toByteArray();
return byteArray;
}
/**
* 构造带签名的交易
*
* @param transaction
* @return
*/
public static TransactionAllProtobuf.Transaction encodeProtobufWithSign2(Transaction transaction) {
TransactionAllProtobuf.Transaction.Builder builder = TransactionAllProtobuf.Transaction.newBuilder();
builder.setExecer(ByteString.copyFrom(transaction.getExecer()));
builder.setExpire(transaction.getExpire());
builder.setFee(transaction.getFee());
builder.setNonce(transaction.getNonce());
builder.setPayload(ByteString.copyFrom(transaction.getPayload()));
builder.setTo(transaction.getTo());
builder.setChainID(transaction.getChainID());
TransactionAllProtobuf.Signature.Builder signatureBuilder = builder.getSignatureBuilder();
signatureBuilder.setPubkey(ByteString.copyFrom(transaction.getSignature().getPubkey()));
signatureBuilder.setTy(transaction.getSignature().getTy());
signatureBuilder.setSignature(ByteString.copyFrom(transaction.getSignature().getSignature()));
TransactionAllProtobuf.Signature signatureBuild = signatureBuilder.build();
builder.setSignature(signatureBuild);
TransactionAllProtobuf.Transaction build = builder.build();
return build;
}
/**
* 构造带签名的交易
*
* @param transaction
* @return
*/
public static byte[] encodeProtobufWithSign(Transaction transaction) {
TransactionAllProtobuf.Transaction.Builder builder = TransactionAllProtobuf.Transaction.newBuilder();
builder.setExecer(ByteString.copyFrom(transaction.getExecer()));
builder.setExpire(transaction.getExpire());
builder.setFee(transaction.getFee());
builder.setNonce(transaction.getNonce());
builder.setPayload(ByteString.copyFrom(transaction.getPayload()));
builder.setTo(transaction.getTo());
builder.setChainID(transaction.getChainID());
TransactionAllProtobuf.Signature.Builder signatureBuilder = builder.getSignatureBuilder();
signatureBuilder.setPubkey(ByteString.copyFrom(transaction.getSignature().getPubkey()));
signatureBuilder.setTy(transaction.getSignature().getTy());
signatureBuilder.setSignature(ByteString.copyFrom(transaction.getSignature().getSignature()));
TransactionAllProtobuf.Signature signatureBuild = signatureBuilder.build();
builder.setSignature(signatureBuild);
TransactionAllProtobuf.Transaction build = builder.build();
byte[] byteArray = build.toByteArray();
return byteArray;
}
/**
* 签名
*
* @param signType 签名类型
* @param data 加密数据
* @param privateKey 私钥
* @param transaction 交易
*/
private static void sign(SignType signType, byte[] data, byte[] privateKey, byte[] uid, Transaction transaction) {
switch (signType) {
case SECP256K1: {
Signature btcCoinSign = btcCoinSign(data, privateKey);
transaction.setSignature(btcCoinSign);
}
break;
case ETH_SECP256K1: {
Signature btcCoinSign = btcCoinSign(data, privateKey, signType);
transaction.setSignature(btcCoinSign);
}
break;
case SM2:
case ETH_SM2: {
SM2KeyPair keyPair = SM2Util.fromPrivateKey(privateKey);
byte[] derSignBytes;
try {
derSignBytes = SM2Util.sign(data, uid, keyPair);
} catch (IOException e) {
break;
}
Signature signature = new Signature();
signature.setPubkey(keyPair.getPublicKey().getEncoded(true));
signature.setSignature(derSignBytes);
signature.setTy(signType.getType());
transaction.setSignature(signature);
}
break;
case ED25519:
case ETH_ED25519: {
Ecc25519Helper helper1 = new Ecc25519Helper(privateKey);
byte[] publicKey = helper1.getKeyHolder().getPublicKeySignature();
byte[] sign = helper1.sign(data);
Signature signature = new Signature();
signature.setPubkey(publicKey);
signature.setSignature(sign);
signature.setTy(signType.getType());
transaction.setSignature(signature);
}
break;
default:
break;
}
}
private static Signature sign(byte[] data, byte[] privateKey, SignType signType) {
byte[] sha256 = TransactionUtil.Sha256(data);
Sha256Hash sha256Hash = Sha256Hash.wrap(sha256);
ECKey ecKey = ECKey.fromPrivate(privateKey);
ECKey.ECDSASignature ecdsas = ecKey.sign(sha256Hash);
byte[] signByte = ecdsas.encodeToDER();
Signature signature = new Signature();
signature.setPubkey(ecKey.getPubKey());
signature.setSignature(signByte);
signature.setTy(signType.getType());
return signature;
}
/**
* @param privateKey 私钥
* @param expire 秒数
* @param txHex 上一步CreateNoBalanceTransaction生成的交易hash 16进制
* @param index 是签名交易组,则为要签名的交易序号,从1开始,小于等于0则为签名组内全部交易
* @return
* @description 本地签名
*/
public static String signRawTx(String privateKey, long expire, String txHex, Integer index) throws Exception {
// 1.检查私钥是否存在 ->存在:->byte
if (StringUtil.isEmpty(privateKey)) {
throw new Exception("privateKey not Exist");
}
byte[] privKeyBytes = HexUtil.fromHexString(privateKey);
RawTransactionProtobuf.Transaction.Builder txBuilder = RawTransactionProtobuf.Transaction.newBuilder();
RawTransactionProtobuf.Transaction rawtransactionProtobuf = txBuilder.mergeFrom(HexUtil.fromHexString(txHex))
.build();
long changedExpire = getExpire(expire);
txBuilder.setExpire(changedExpire);
// 如果执行器为privacy 暂时不处理
/*
* if(Arrays.equals(ExecerPrivacy,rawtransactionProtobuf.getExecer().
* toByteArray ())) { //signTxWithPrivacy }
*/
int groupCount = rawtransactionProtobuf.getGroupCount();
if (groupCount < 0 || groupCount == 1 || groupCount > 20) {
throw new Exception("ErrTxGroupCount");
} else if (groupCount > 0) {
byte[] txsBytes = rawtransactionProtobuf.getHeader().toByteArray();
RawTransactionProtobuf.Transactions.Builder txsBuilder = RawTransactionProtobuf.Transactions.newBuilder();
RawTransactionProtobuf.Transactions txs = txsBuilder.mergeFrom(txsBytes).build();
List<RawTransactionProtobuf.Transaction> txsList = txs.getTxsList();
if (index > txsList.size()) {
throw new Exception("ErrIndex");
}
if (index <= 0) {
for (int i = 0; i < txsList.size(); i++) {
RawTransactionProtobuf.Transaction signTransactionsN = signTransactionsN(i, txsList, privKeyBytes);
txsList.set(i, signTransactionsN);
}
RawTransactionProtobuf.Transaction transaction = txsList.get(0);
transaction.toBuilder().setHeader(ByteString.copyFrom(txs.toByteArray()));
byte[] byteArray = transaction.toByteArray();
String signHexString = HexUtil.toHexString(byteArray);
return signHexString;
}
index--;
RawTransactionProtobuf.Transaction signTransactionsN = signTransactionsN(index, txsList, privKeyBytes);
txsList.set(index, signTransactionsN);
RawTransactionProtobuf.Transaction transactionFirst = txsList.get(0);
transactionFirst.toBuilder().setHeader(ByteString.copyFrom(txs.toByteArray()));