forked from tronprotocol/wallet-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWalletApi.java
More file actions
3088 lines (2723 loc) · 115 KB
/
WalletApi.java
File metadata and controls
3088 lines (2723 loc) · 115 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 org.tron.walletserver;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigObject;
import io.grpc.Status;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Paths;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.util.encoders.Hex;
import org.tron.api.GrpcAPI;
import org.tron.api.GrpcAPI.AccountNetMessage;
import org.tron.api.GrpcAPI.AccountResourceMessage;
import org.tron.api.GrpcAPI.AssetIssueList;
import org.tron.api.GrpcAPI.BlockExtention;
import org.tron.api.GrpcAPI.BlockList;
import org.tron.api.GrpcAPI.BlockListExtention;
import org.tron.api.GrpcAPI.BytesMessage;
import org.tron.api.GrpcAPI.DecryptNotes;
import org.tron.api.GrpcAPI.DecryptNotesMarked;
import org.tron.api.GrpcAPI.DecryptNotesTRC20;
import org.tron.api.GrpcAPI.DelegatedResourceList;
import org.tron.api.GrpcAPI.DiversifierMessage;
import org.tron.api.GrpcAPI.EstimateEnergyMessage;
import org.tron.api.GrpcAPI.ExchangeList;
import org.tron.api.GrpcAPI.ExpandedSpendingKeyMessage;
import org.tron.api.GrpcAPI.IncomingViewingKeyDiversifierMessage;
import org.tron.api.GrpcAPI.IncomingViewingKeyMessage;
import org.tron.api.GrpcAPI.IvkDecryptAndMarkParameters;
import org.tron.api.GrpcAPI.IvkDecryptParameters;
import org.tron.api.GrpcAPI.IvkDecryptTRC20Parameters;
import org.tron.api.GrpcAPI.NfParameters;
import org.tron.api.GrpcAPI.NfTRC20Parameters;
import org.tron.api.GrpcAPI.NodeList;
import org.tron.api.GrpcAPI.NoteParameters;
import org.tron.api.GrpcAPI.NullifierResult;
import org.tron.api.GrpcAPI.OvkDecryptParameters;
import org.tron.api.GrpcAPI.OvkDecryptTRC20Parameters;
import org.tron.api.GrpcAPI.PaymentAddressMessage;
import org.tron.api.GrpcAPI.PricesResponseMessage;
import org.tron.api.GrpcAPI.PrivateParameters;
import org.tron.api.GrpcAPI.PrivateParametersWithoutAsk;
import org.tron.api.GrpcAPI.PrivateShieldedTRC20Parameters;
import org.tron.api.GrpcAPI.PrivateShieldedTRC20ParametersWithoutAsk;
import org.tron.api.GrpcAPI.ProposalList;
import org.tron.api.GrpcAPI.Return;
import org.tron.api.GrpcAPI.ShieldedTRC20Parameters;
import org.tron.api.GrpcAPI.ShieldedTRC20TriggerContractParameters;
import org.tron.api.GrpcAPI.SpendAuthSigParameters;
import org.tron.api.GrpcAPI.SpendResult;
import org.tron.api.GrpcAPI.TransactionApprovedList;
import org.tron.api.GrpcAPI.TransactionExtention;
import org.tron.api.GrpcAPI.TransactionInfoList;
import org.tron.api.GrpcAPI.TransactionList;
import org.tron.api.GrpcAPI.TransactionListExtention;
import org.tron.api.GrpcAPI.TransactionSignWeight;
import org.tron.api.GrpcAPI.TransactionSignWeight.Result.response_code;
import org.tron.api.GrpcAPI.ViewingKeyMessage;
import org.tron.api.GrpcAPI.WitnessList;
import org.tron.common.crypto.ECKey;
import org.tron.common.crypto.Hash;
import org.tron.common.crypto.Sha256Sm3Hash;
import org.tron.common.crypto.SignInterface;
import org.tron.common.crypto.sm2.SM2;
import org.tron.common.utils.Base58;
import org.tron.common.utils.ByteArray;
import org.tron.common.utils.PathUtil;
import org.tron.common.utils.TransactionUtils;
import org.tron.common.utils.Utils;
import org.tron.common.zksnark.JLibrustzcash;
import org.tron.common.zksnark.LibrustzcashParam.SpendSigParams;
import org.tron.core.config.Configuration;
import org.tron.core.config.Parameter.CommonConstant;
import org.tron.core.exception.CancelException;
import org.tron.core.exception.CipherException;
import org.tron.keystore.CheckStrength;
import org.tron.keystore.Credentials;
import org.tron.mnemonic.Mnemonic;
import org.tron.mnemonic.MnemonicFile;
import org.tron.mnemonic.MnemonicUtils;
import org.tron.keystore.Wallet;
import org.tron.keystore.WalletFile;
import org.tron.keystore.WalletUtils;
import org.tron.protos.Protocol;
import org.tron.protos.Protocol.Account;
import org.tron.protos.Protocol.Block;
import org.tron.protos.Protocol.ChainParameters;
import org.tron.protos.Protocol.Exchange;
import org.tron.protos.Protocol.Key;
import org.tron.protos.Protocol.MarketOrder;
import org.tron.protos.Protocol.MarketOrderList;
import org.tron.protos.Protocol.MarketOrderPairList;
import org.tron.protos.Protocol.MarketPriceList;
import org.tron.protos.Protocol.Permission;
import org.tron.protos.Protocol.Proposal;
import org.tron.protos.Protocol.Transaction;
import org.tron.protos.Protocol.Transaction.Contract.ContractType;
import org.tron.protos.Protocol.Transaction.Result;
import org.tron.protos.Protocol.TransactionInfo;
import org.tron.protos.Protocol.Witness;
import org.tron.protos.contract.AccountContract.AccountCreateContract;
import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract;
import org.tron.protos.contract.AccountContract.AccountUpdateContract;
import org.tron.protos.contract.AccountContract.SetAccountIdContract;
import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract;
import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract;
import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract;
import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract;
import org.tron.protos.contract.AssetIssueContractOuterClass.UpdateAssetContract;
import org.tron.protos.contract.BalanceContract;
import org.tron.protos.contract.BalanceContract.CancelAllUnfreezeV2Contract;
import org.tron.protos.contract.BalanceContract.FreezeBalanceContract;
import org.tron.protos.contract.BalanceContract.TransferContract;
import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract;
import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract;
import org.tron.protos.contract.ExchangeContract.ExchangeCreateContract;
import org.tron.protos.contract.ExchangeContract.ExchangeInjectContract;
import org.tron.protos.contract.ExchangeContract.ExchangeTransactionContract;
import org.tron.protos.contract.ExchangeContract.ExchangeWithdrawContract;
import org.tron.protos.contract.MarketContract.MarketCancelOrderContract;
import org.tron.protos.contract.MarketContract.MarketSellAssetContract;
import org.tron.protos.contract.ProposalContract.ProposalApproveContract;
import org.tron.protos.contract.ProposalContract.ProposalCreateContract;
import org.tron.protos.contract.ProposalContract.ProposalDeleteContract;
import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo;
import org.tron.protos.contract.ShieldContract.OutputPointInfo;
import org.tron.protos.contract.ShieldContract.ShieldedTransferContract;
import org.tron.protos.contract.ShieldContract.SpendDescription;
import org.tron.protos.contract.SmartContractOuterClass.ClearABIContract;
import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract;
import org.tron.protos.contract.SmartContractOuterClass.SmartContract;
import org.tron.protos.contract.SmartContractOuterClass.SmartContractDataWrapper;
import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract;
import org.tron.protos.contract.SmartContractOuterClass.UpdateEnergyLimitContract;
import org.tron.protos.contract.SmartContractOuterClass.UpdateSettingContract;
import org.tron.protos.contract.StorageContract.BuyStorageBytesContract;
import org.tron.protos.contract.StorageContract.BuyStorageContract;
import org.tron.protos.contract.StorageContract.SellStorageContract;
import org.tron.protos.contract.StorageContract.UpdateBrokerageContract;
import org.tron.protos.contract.WitnessContract.VoteWitnessContract;
import org.tron.protos.contract.WitnessContract.WitnessCreateContract;
import org.tron.protos.contract.WitnessContract.WitnessUpdateContract;
@Slf4j
public class WalletApi {
private static final String FilePath = "Wallet";
private static final String MnemonicFilePath = "Mnemonic";
private List<WalletFile> walletFile = new ArrayList<>();
private boolean loginState = false;
private byte[] address;
private static byte addressPreFixByte = CommonConstant.ADD_PRE_FIX_BYTE_TESTNET;
private static int rpcVersion = 0;
private static boolean isEckey = true;
private static GrpcClient rpcCli = init();
public static GrpcClient init() {
Config config = Configuration.getByPath("config.conf");
String fullNode = "";
String solidityNode = "";
if (config.hasPath("soliditynode.ip.list")) {
solidityNode = config.getStringList("soliditynode.ip.list").get(0);
}
if (config.hasPath("fullnode.ip.list")) {
fullNode = config.getStringList("fullnode.ip.list").get(0);
}
if (config.hasPath("net.type") && "mainnet".equalsIgnoreCase(config.getString("net.type"))) {
WalletApi.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET);
} else {
WalletApi.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_TESTNET);
}
if (config.hasPath("RPC_version")) {
rpcVersion = config.getInt("RPC_version");
System.out.println("WalletApi getRpcVsersion: " + rpcVersion);
}
if (config.hasPath("crypto.engine")) {
isEckey = config.getString("crypto.engine").equalsIgnoreCase("eckey");
System.out.println("WalletApi getConfig isEckey: " + isEckey);
}
return new GrpcClient(fullNode, solidityNode);
}
public static String selectFullNode() {
Map<String, String> witnessMap = new HashMap<>();
Config config = Configuration.getByPath("config.conf");
List list = config.getObjectList("witnesses.witnessList");
for (int i = 0; i < list.size(); i++) {
ConfigObject obj = (ConfigObject) list.get(i);
String ip = obj.get("ip").unwrapped().toString();
String url = obj.get("url").unwrapped().toString();
witnessMap.put(url, ip);
}
Optional<WitnessList> result = rpcCli.listWitnesses();
long minMissedNum = 100000000L;
String minMissedWitness = "";
if (result.isPresent()) {
List<Witness> witnessList = result.get().getWitnessesList();
for (Witness witness : witnessList) {
String url = witness.getUrl();
long missedBlocks = witness.getTotalMissed();
if (missedBlocks < minMissedNum) {
minMissedNum = missedBlocks;
minMissedWitness = url;
}
}
}
if (witnessMap.containsKey(minMissedWitness)) {
return witnessMap.get(minMissedWitness);
} else {
return "";
}
}
public static byte getAddressPreFixByte() {
return addressPreFixByte;
}
public static void setAddressPreFixByte(byte addressPreFixByte) {
WalletApi.addressPreFixByte = addressPreFixByte;
}
public static int getRpcVersion() {
return rpcVersion;
}
/**
* Creates a new WalletApi with a random ECKey or no ECKey.
*/
public static WalletFile CreateWalletFile(byte[] password) throws CipherException, IOException {
WalletFile walletFile = null;
SecureRandom secureRandom = Utils.getRandom();
List<String> mnemonicWords = MnemonicUtils.generateMnemonic(secureRandom);
//System.out.println("generateMnemonic words:" + StringUtils.join(mnemonicWords, " "));
byte[] priKey = MnemonicUtils.getPrivateKeyFromMnemonic(mnemonicWords);
if (isEckey) {
ECKey ecKey = new ECKey(priKey, true);
walletFile = Wallet.createStandard(password, ecKey);
storeMnemonicWords(password, ecKey, mnemonicWords);
} else {
SM2 sm2 = new SM2(priKey, true);
walletFile = Wallet.createStandard(password, sm2);
storeMnemonicWords(password, sm2, mnemonicWords);
}
return walletFile;
}
public static void storeMnemonicWords(byte[] password, SignInterface ecKeySm2Pair, List<String> mnemonicWords) throws CipherException, IOException {
MnemonicFile mnemonicFile = Mnemonic.createStandard(password, ecKeySm2Pair, mnemonicWords);
String keystoreName = MnemonicUtils.store2Keystore(mnemonicFile);
System.out.println("mnemonic file : ."
+ File.separator + "Mnemonic" + File.separator
+ keystoreName);
}
// Create Wallet with a pritKey
public static WalletFile CreateWalletFile(byte[] password, byte[] priKey, List<String> mnemonicWords) throws CipherException, IOException {
WalletFile walletFile = null;
if (isEckey) {
ECKey ecKey = ECKey.fromPrivate(priKey);
walletFile = Wallet.createStandard(password, ecKey);
if (mnemonicWords !=null && !mnemonicWords.isEmpty()) {
storeMnemonicWords(password, ecKey, mnemonicWords);
}
} else {
SM2 sm2 = SM2.fromPrivate(priKey);
walletFile = Wallet.createStandard(password, sm2);
if (mnemonicWords !=null && !mnemonicWords.isEmpty()) {
storeMnemonicWords(password, sm2, mnemonicWords);
}
}
return walletFile;
}
public boolean isLoginState() {
return loginState;
}
public void logout() {
loginState = false;
walletFile.clear();
this.walletFile = null;
}
public void setLogin() {
loginState = true;
}
public boolean checkPassword(byte[] passwd) throws CipherException {
return Wallet.validPassword(passwd, this.walletFile.get(0));
}
/**
* Creates a Wallet with an existing ECKey.
*/
public WalletApi(WalletFile walletFile) {
if (this.walletFile.isEmpty()) {
this.walletFile.add(walletFile);
} else {
this.walletFile.set(0, walletFile);
}
this.address = decodeFromBase58Check(walletFile.getAddress());
}
public ECKey getEcKey(WalletFile walletFile, byte[] password) throws CipherException {
return Wallet.decrypt(password, walletFile);
}
public SM2 getSM2(WalletFile walletFile, byte[] password) throws CipherException {
return Wallet.decryptSM2(password, walletFile);
}
public byte[] getPrivateBytes(byte[] password) throws CipherException, IOException {
WalletFile walletFile = loadWalletFile();
return Wallet.decrypt2PrivateBytes(password, walletFile);
}
public String exportKeystore(String walletChannel, File exportFullDir) throws IOException {
String ret = null;
try {
WalletFile walletFile = loadWalletFile();
String walletAddress = walletFile.getAddress();
String walletHexAddress = getHexAddress(walletFile.getAddress());
walletFile.setAddress(walletHexAddress);
ret = WalletUtils.exportWalletFile(walletFile, walletAddress, exportFullDir);
} catch (Exception e) {
System.out.println("exportKeystore failed. " + e.getMessage());
}
return ret;
}
public boolean importKeystore(String walletChannel, String walletImportPath) throws IOException {
String importFilePath = PathUtil.toAbsolutePath(walletImportPath);
File importFile = new File(importFilePath);
//WalletFile walletFile =
//WalletUtils.importWalletFile(walletFile, importFile);
return true;
}
public byte[] getAddress() {
return address;
}
public static String store2Keystore(WalletFile walletFile) throws IOException {
if (walletFile == null) {
System.out.println("Warning: Store wallet failed, walletFile is null !!");
return null;
}
if (WalletUtils.hasStoreFile(walletFile.getAddress(), FilePath)) {
WalletUtils.deleteStoreFile(walletFile.getAddress(), FilePath);
}
File file = new File(FilePath);
if (!file.exists()) {
if (!file.mkdir()) {
throw new IOException("Make directory failed!");
}
} else {
if (!file.isDirectory()) {
if (file.delete()) {
if (!file.mkdir()) {
throw new IOException("Make directory failed!");
}
} else {
throw new IOException("File exists and can not be deleted!");
}
}
}
return WalletUtils.generateWalletFile(walletFile, file);
}
public static File selcetWalletFile() {
File file = new File(FilePath);
if (!file.exists() || !file.isDirectory()) {
return null;
}
File[] wallets = file.listFiles();
if (ArrayUtils.isEmpty(wallets)) {
return null;
}
File wallet;
if (wallets.length > 1) {
for (int i = 0; i < wallets.length; i++) {
System.out.println("The " + (i + 1) + "th keystore file name is " + wallets[i].getName());
}
System.out.println("Please choose between 1 and " + wallets.length);
Scanner in = new Scanner(System.in);
while (true) {
String input = in.nextLine().trim();
String num = input.split("\\s+")[0];
int n;
try {
n = new Integer(num);
} catch (NumberFormatException e) {
System.out.println("Invaild number of " + num);
System.out.println("Please choose again between 1 and " + wallets.length);
continue;
}
if (n < 1 || n > wallets.length) {
System.out.println("Please choose again between 1 and " + wallets.length);
continue;
}
wallet = wallets[n - 1];
break;
}
} else {
wallet = wallets[0];
}
return wallet;
}
public static File selcetMnemonicFile() {
File file = new File(MnemonicFilePath);
if (!file.exists() || !file.isDirectory()) {
return null;
}
File[] mnemonicFiles = file.listFiles();
if (ArrayUtils.isEmpty(mnemonicFiles)) {
return null;
}
File mnemonicFile;
if (mnemonicFiles.length > 1) {
for (int i = 0; i < mnemonicFiles.length; i++) {
System.out.println("The " + (i + 1) + "th mnemonic file name is " + mnemonicFiles[i].getName());
}
System.out.println("Please choose between 1 and " + mnemonicFiles.length);
Scanner in = new Scanner(System.in);
while (true) {
String input = in.nextLine().trim();
String num = input.split("\\s+")[0];
int n;
try {
n = new Integer(num);
} catch (NumberFormatException e) {
System.out.println("Invaild number of " + num);
System.out.println("Please choose again between 1 and " + mnemonicFiles.length);
continue;
}
if (n < 1 || n > mnemonicFiles.length) {
System.out.println("Please choose again between 1 and " + mnemonicFiles.length);
continue;
}
mnemonicFile = mnemonicFiles[n - 1];
break;
}
} else {
mnemonicFile = mnemonicFiles[0];
}
return mnemonicFile;
}
public WalletFile selcetWalletFileE() throws IOException {
File file = selcetWalletFile();
if (file == null) {
throw new IOException(
"No keystore file found, please use registerwallet or importwallet first!");
}
String name = file.getName();
for (WalletFile wallet : this.walletFile) {
String address = wallet.getAddress();
if (name.contains(address)) {
return wallet;
}
}
WalletFile wallet = WalletUtils.loadWalletFile(file);
this.walletFile.add(wallet);
return wallet;
}
public static boolean changeKeystorePassword(byte[] oldPassword, byte[] newPassowrd)
throws IOException, CipherException {
File wallet = selcetWalletFile();
if (wallet == null) {
throw new IOException(
"No keystore file found, please use registerwallet or importwallet first!");
}
Credentials credentials = WalletUtils.loadCredentials(oldPassword, wallet);
WalletUtils.updateWalletFile(newPassowrd, credentials.getPair(), wallet, true);
// udpate the password of mnemonicFile
String ownerAddress = credentials.getAddress();
File mnemonicFile = Paths.get("Mnemonic", ownerAddress + ".json").toFile();
if (mnemonicFile.exists()) {
try {
byte[] mnemonicBytes = MnemonicUtils.getMnemonicBytes(oldPassword, mnemonicFile);
List<String> words = MnemonicUtils.stringToMnemonicWords(new String(mnemonicBytes));
MnemonicUtils.updateMnemonicFile(newPassowrd, credentials.getPair(), mnemonicFile, true, words);
} catch (Exception e) {
System.out.println("update mnemonic file failed, please check the mnemonic file");
}
}
return true;
}
private static WalletFile loadWalletFile() throws IOException {
File wallet = selcetWalletFile();
if (wallet == null) {
throw new IOException(
"No keystore file found, please use registerwallet or importwallet first!");
}
return WalletUtils.loadWalletFile(wallet);
}
/**
* load a Wallet from keystore
*/
public static WalletApi loadWalletFromKeystore() throws IOException {
WalletFile walletFile = loadWalletFile();
WalletApi walletApi = new WalletApi(walletFile);
return walletApi;
}
public Account queryAccount() {
return queryAccount(getAddress());
}
public static Account queryAccount(byte[] address) {
return rpcCli.queryAccount(address); // call rpc
}
public static Account queryAccountById(String accountId) {
return rpcCli.queryAccountById(accountId);
}
private boolean confirm() {
Scanner in = new Scanner(System.in);
while (true) {
String input = in.nextLine().trim();
String str = input.split("\\s+")[0];
if ("y".equalsIgnoreCase(str)) {
return true;
} else {
return false;
}
}
}
private Transaction signTransaction(Transaction transaction)
throws CipherException, IOException, CancelException {
if (transaction.getRawData().getTimestamp() == 0) {
transaction = TransactionUtils.setTimestamp(transaction);
}
transaction = TransactionUtils.setExpirationTime(transaction);
String tipsString = "Please confirm and input your permission id, if input y or Y means "
+ "default 0, other non-numeric characters will cancel transaction.";
transaction = TransactionUtils.setPermissionId(transaction, tipsString);
while (true) {
System.out.println("Please choose your key for sign.");
WalletFile walletFile = selcetWalletFileE();
System.out.println("Please input your password.");
char[] password = Utils.inputPassword(false);
byte[] passwd = org.tron.keystore.StringUtils.char2Byte(password);
org.tron.keystore.StringUtils.clear(password);
if (isEckey) {
transaction = TransactionUtils.sign(transaction, this.getEcKey(walletFile, passwd));
} else {
transaction = TransactionUtils.sign(transaction, this.getSM2(walletFile, passwd));
}
org.tron.keystore.StringUtils.clear(passwd);
TransactionSignWeight weight = getTransactionSignWeight(transaction);
if (weight.getResult().getCode() == response_code.ENOUGH_PERMISSION) {
break;
}
if (weight.getResult().getCode() == response_code.NOT_ENOUGH_PERMISSION) {
System.out.println("Current signWeight is:");
System.out.println(Utils.printTransactionSignWeight(weight));
System.out.println("Please confirm if continue add signature enter y or Y, else any other");
if (!confirm()) {
showTransactionAfterSign(transaction);
throw new CancelException("User cancelled");
}
continue;
}
throw new CancelException(weight.getResult().getMessage());
}
return transaction;
}
private Transaction signOnlyForShieldedTransaction(Transaction transaction)
throws CipherException, IOException, CancelException {
String tipsString = "Please confirm and input your permission id, if input y or Y means "
+ "default 0, other non-numeric characters will cancel transaction.";
transaction = TransactionUtils.setPermissionId(transaction, tipsString);
while (true) {
System.out.println("Please choose your key for sign.");
WalletFile walletFile = selcetWalletFileE();
System.out.println("Please input your password.");
char[] password = Utils.inputPassword(false);
byte[] passwd = org.tron.keystore.StringUtils.char2Byte(password);
org.tron.keystore.StringUtils.clear(password);
if (isEckey) {
transaction = TransactionUtils.sign(transaction, this.getEcKey(walletFile, passwd));
} else {
transaction = TransactionUtils.sign(transaction, this.getSM2(walletFile, passwd));
}
org.tron.keystore.StringUtils.clear(passwd);
TransactionSignWeight weight = getTransactionSignWeight(transaction);
if (weight.getResult().getCode() == response_code.ENOUGH_PERMISSION) {
break;
}
if (weight.getResult().getCode() == response_code.NOT_ENOUGH_PERMISSION) {
System.out.println("Current signWeight is:");
System.out.println(Utils.printTransactionSignWeight(weight));
System.out.println("Please confirm if continue add signature enter y or Y, else any other");
if (!confirm()) {
throw new CancelException("User cancelled");
}
continue;
}
throw new CancelException(weight.getResult().getMessage());
}
return transaction;
}
private boolean processTransactionExtention(TransactionExtention transactionExtention)
throws IOException, CipherException, CancelException {
if (transactionExtention == null) {
return false;
}
Return ret = transactionExtention.getResult();
if (!ret.getResult()) {
System.out.println("Code = " + ret.getCode());
System.out.println("Message = " + ret.getMessage().toStringUtf8());
return false;
}
Transaction transaction = transactionExtention.getTransaction();
if (transaction == null || transaction.getRawData().getContractCount() == 0) {
System.out.println("Transaction is empty");
return false;
}
if (transaction.getRawData().getContract(0).getType()
== ContractType.ShieldedTransferContract) {
return false;
}
System.out.println(Utils.printTransactionExceptId(transactionExtention.getTransaction()));
System.out.println("before sign transaction hex string is " +
ByteArray.toHexString(transaction.toByteArray()));
transaction = signTransaction(transaction);
showTransactionAfterSign(transaction);
return rpcCli.broadcastTransaction(transaction);
}
private void showTransactionAfterSign(Transaction transaction)
throws InvalidProtocolBufferException {
System.out.println("after sign transaction hex string is " +
ByteArray.toHexString(transaction.toByteArray()));
System.out.println("txid is " +
ByteArray.toHexString(Sha256Sm3Hash.hash(transaction.getRawData().toByteArray())));
if (transaction.getRawData().getContract(0).getType() == ContractType.CreateSmartContract) {
CreateSmartContract createSmartContract = transaction.getRawData().getContract(0)
.getParameter().unpack(CreateSmartContract.class);
byte[] contractAddress = generateContractAddress(
createSmartContract.getOwnerAddress().toByteArray(), transaction);
System.out.println(
"Your smart contract address will be: " + WalletApi.encode58Check(contractAddress));
}
}
private static boolean processShieldedTransaction(TransactionExtention transactionExtention,
WalletApi wallet)
throws IOException, CipherException, CancelException {
if (transactionExtention == null) {
return false;
}
Return ret = transactionExtention.getResult();
if (!ret.getResult()) {
System.out.println("Code = " + ret.getCode());
System.out.println("Message = " + ret.getMessage().toStringUtf8());
return false;
}
Transaction transaction = transactionExtention.getTransaction();
if (transaction == null || transaction.getRawData().getContractCount() == 0) {
System.out.println("Transaction is empty");
return false;
}
if (transaction.getRawData().getContract(0).getType()
!= ContractType.ShieldedTransferContract) {
return false;
}
System.out.println(Utils.printTransactionExceptId(transactionExtention.getTransaction()));
Any any = transaction.getRawData().getContract(0).getParameter();
ShieldedTransferContract shieldedTransferContract = any.unpack(ShieldedTransferContract.class);
if (shieldedTransferContract.getFromAmount() > 0) {
if (wallet == null || !wallet.isLoginState()) {
System.out.println("Warning: processShieldedTransaction failed, Please login first !!");
return false;
}
transaction = wallet.signOnlyForShieldedTransaction(transaction);
}
System.out.println(
"transaction hex string is " + ByteArray.toHexString(transaction.toByteArray()));
System.out.println(
"txid is "
+ ByteArray.toHexString(Sha256Sm3Hash.hash(transaction.getRawData().toByteArray())));
return rpcCli.broadcastTransaction(transaction);
}
private boolean processTransaction(Transaction transaction)
throws IOException, CipherException, CancelException {
if (transaction == null || transaction.getRawData().getContractCount() == 0) {
return false;
}
System.out.println(Utils.printTransactionExceptId(transaction));
System.out.println(
"before sign transaction hex string is "
+ ByteArray.toHexString(transaction.toByteArray()));
transaction = signTransaction(transaction);
showTransactionAfterSign(transaction);
return rpcCli.broadcastTransaction(transaction);
}
public static TransactionSignWeight getTransactionSignWeight(Transaction transaction) {
return rpcCli.getTransactionSignWeight(transaction);
}
public static TransactionApprovedList getTransactionApprovedList(Transaction transaction) {
return rpcCli.getTransactionApprovedList(transaction);
}
public boolean sendCoin(byte[] owner, byte[] to, long amount)
throws CipherException, IOException, CancelException {
if (owner == null) {
owner = getAddress();
}
TransferContract contract = createTransferContract(to, owner, amount);
if (rpcVersion == 2) {
TransactionExtention transactionExtention = rpcCli.createTransaction2(contract);
return processTransactionExtention(transactionExtention);
} else {
Transaction transaction = rpcCli.createTransaction(contract);
return processTransaction(transaction);
}
}
public boolean updateAccount(byte[] owner, byte[] accountNameBytes)
throws CipherException, IOException, CancelException {
if (owner == null) {
owner = getAddress();
}
AccountUpdateContract contract = createAccountUpdateContract(accountNameBytes, owner);
if (rpcVersion == 2) {
TransactionExtention transactionExtention = rpcCli.createTransaction2(contract);
return processTransactionExtention(transactionExtention);
} else {
Transaction transaction = rpcCli.createTransaction(contract);
return processTransaction(transaction);
}
}
public boolean setAccountId(byte[] owner, byte[] accountIdBytes)
throws CipherException, IOException, CancelException {
if (owner == null) {
owner = getAddress();
}
SetAccountIdContract contract = createSetAccountIdContract(accountIdBytes, owner);
Transaction transaction = rpcCli.createTransaction(contract);
if (transaction == null || transaction.getRawData().getContractCount() == 0) {
return false;
}
return processTransaction(transaction);
}
public boolean updateAsset(
byte[] owner, byte[] description, byte[] url, long newLimit, long newPublicLimit)
throws CipherException, IOException, CancelException {
if (owner == null) {
owner = getAddress();
}
UpdateAssetContract contract =
createUpdateAssetContract(owner, description, url, newLimit, newPublicLimit);
if (rpcVersion == 2) {
TransactionExtention transactionExtention = rpcCli.createTransaction2(contract);
return processTransactionExtention(transactionExtention);
} else {
Transaction transaction = rpcCli.createTransaction(contract);
return processTransaction(transaction);
}
}
public boolean transferAsset(byte[] owner, byte[] to, byte[] assertName, long amount)
throws CipherException, IOException, CancelException {
if (owner == null) {
owner = getAddress();
}
TransferAssetContract contract = createTransferAssetContract(to, assertName, owner, amount);
if (rpcVersion == 2) {
TransactionExtention transactionExtention = rpcCli.createTransferAssetTransaction2(contract);
return processTransactionExtention(transactionExtention);
} else {
Transaction transaction = rpcCli.createTransferAssetTransaction(contract);
return processTransaction(transaction);
}
}
public boolean participateAssetIssue(byte[] owner, byte[] to, byte[] assertName, long amount)
throws CipherException, IOException, CancelException {
if (owner == null) {
owner = getAddress();
}
ParticipateAssetIssueContract contract =
participateAssetIssueContract(to, assertName, owner, amount);
if (rpcVersion == 2) {
TransactionExtention transactionExtention =
rpcCli.createParticipateAssetIssueTransaction2(contract);
return processTransactionExtention(transactionExtention);
} else {
Transaction transaction = rpcCli.createParticipateAssetIssueTransaction(contract);
return processTransaction(transaction);
}
}
public static boolean broadcastTransaction(byte[] transactionBytes)
throws InvalidProtocolBufferException {
Transaction transaction = Transaction.parseFrom(transactionBytes);
return rpcCli.broadcastTransaction(transaction);
}
public static boolean broadcastTransaction(Transaction transaction) {
return rpcCli.broadcastTransaction(transaction);
}
public boolean createAssetIssue(AssetIssueContract contract)
throws CipherException, IOException, CancelException {
if (rpcVersion == 2) {
TransactionExtention transactionExtention = rpcCli.createAssetIssue2(contract);
return processTransactionExtention(transactionExtention);
} else {
Transaction transaction = rpcCli.createAssetIssue(contract);
return processTransaction(transaction);
}
}
public boolean createAccount(byte[] owner, byte[] address)
throws CipherException, IOException, CancelException {
if (owner == null) {
owner = getAddress();
}
AccountCreateContract contract = createAccountCreateContract(owner, address);
if (rpcVersion == 2) {
TransactionExtention transactionExtention = rpcCli.createAccount2(contract);
return processTransactionExtention(transactionExtention);
} else {
Transaction transaction = rpcCli.createAccount(contract);
return processTransaction(transaction);
}
}
public boolean createWitness(byte[] owner, byte[] url)
throws CipherException, IOException, CancelException {
if (owner == null) {
owner = getAddress();
}
WitnessCreateContract contract = createWitnessCreateContract(owner, url);
if (rpcVersion == 2) {
TransactionExtention transactionExtention = rpcCli.createWitness2(contract);
return processTransactionExtention(transactionExtention);
} else {
Transaction transaction = rpcCli.createWitness(contract);
return processTransaction(transaction);
}
}
public boolean updateWitness(byte[] owner, byte[] url)
throws CipherException, IOException, CancelException {
if (owner == null) {
owner = getAddress();
}
WitnessUpdateContract contract = createWitnessUpdateContract(owner, url);
if (rpcVersion == 2) {
TransactionExtention transactionExtention = rpcCli.updateWitness2(contract);
return processTransactionExtention(transactionExtention);
} else {
Transaction transaction = rpcCli.updateWitness(contract);
return processTransaction(transaction);
}
}
public static Block getBlock(long blockNum) {
return rpcCli.getBlock(blockNum);
}
public static BlockExtention getBlock2(long blockNum) {
return rpcCli.getBlock2(blockNum);
}
public static long getTransactionCountByBlockNum(long blockNum) {
return rpcCli.getTransactionCountByBlockNum(blockNum);
}
public boolean voteWitness(byte[] owner, HashMap<String, String> witness)
throws CipherException, IOException, CancelException {
if (owner == null) {
owner = getAddress();
}
VoteWitnessContract contract = createVoteWitnessContract(owner, witness);
if (rpcVersion == 2) {
TransactionExtention transactionExtention = rpcCli.voteWitnessAccount2(contract);
return processTransactionExtention(transactionExtention);
} else {
Transaction transaction = rpcCli.voteWitnessAccount(contract);
return processTransaction(transaction);
}
}
public static TransferContract createTransferContract(byte[] to, byte[] owner, long amount) {
TransferContract.Builder builder = TransferContract.newBuilder();
ByteString bsTo = ByteString.copyFrom(to);
ByteString bsOwner = ByteString.copyFrom(owner);
builder.setToAddress(bsTo);
builder.setOwnerAddress(bsOwner);
builder.setAmount(amount);
return builder.build();
}
public static TransferAssetContract createTransferAssetContract(
byte[] to, byte[] assertName, byte[] owner, long amount) {
TransferAssetContract.Builder builder = TransferAssetContract.newBuilder();
ByteString bsTo = ByteString.copyFrom(to);
ByteString bsName = ByteString.copyFrom(assertName);
ByteString bsOwner = ByteString.copyFrom(owner);
builder.setToAddress(bsTo);
builder.setAssetName(bsName);
builder.setOwnerAddress(bsOwner);
builder.setAmount(amount);
return builder.build();
}
public static ParticipateAssetIssueContract participateAssetIssueContract(
byte[] to, byte[] assertName, byte[] owner, long amount) {
ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder();
ByteString bsTo = ByteString.copyFrom(to);
ByteString bsName = ByteString.copyFrom(assertName);
ByteString bsOwner = ByteString.copyFrom(owner);
builder.setToAddress(bsTo);
builder.setAssetName(bsName);
builder.setOwnerAddress(bsOwner);
builder.setAmount(amount);