forked from tronprotocol/java-tron
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManager.java
More file actions
1564 lines (1368 loc) · 54.4 KB
/
Manager.java
File metadata and controls
1564 lines (1368 loc) · 54.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.tron.core.db;
import static org.tron.core.config.Parameter.ChainConstant.SOLIDIFIED_THRESHOLD;
import static org.tron.core.config.Parameter.NodeConstant.MAX_TRANSACTION_PENDING;
import static org.tron.protos.Protocol.Transaction.Contract.ContractType.TransferAssetContract;
import static org.tron.protos.Protocol.Transaction.Contract.ContractType.TransferContract;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import com.google.protobuf.ByteString;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javafx.util.Pair;
import javax.annotation.PostConstruct;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.joda.time.DateTime;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tron.common.overlay.discover.node.Node;
import org.tron.common.runtime.Runtime;
import org.tron.common.runtime.vm.program.invoke.ProgramInvokeFactoryImpl;
import org.tron.common.storage.DepositImpl;
import org.tron.common.utils.ByteArray;
import org.tron.common.utils.ForkController;
import org.tron.common.utils.SessionOptional;
import org.tron.common.utils.Sha256Hash;
import org.tron.common.utils.StringUtil;
import org.tron.common.utils.Time;
import org.tron.core.Constant;
import org.tron.core.capsule.AccountCapsule;
import org.tron.core.capsule.BlockCapsule;
import org.tron.core.capsule.BlockCapsule.BlockId;
import org.tron.core.capsule.BytesCapsule;
import org.tron.core.capsule.ReceiptCapsule;
import org.tron.core.capsule.TransactionCapsule;
import org.tron.core.capsule.TransactionInfoCapsule;
import org.tron.core.capsule.TransactionResultCapsule;
import org.tron.core.capsule.WitnessCapsule;
import org.tron.core.capsule.utils.BlockUtil;
import org.tron.core.config.Parameter.ChainConstant;
import org.tron.core.config.args.Args;
import org.tron.core.config.args.GenesisBlock;
import org.tron.core.db.KhaosDatabase.KhaosBlock;
import org.tron.core.db2.core.ISession;
import org.tron.core.db2.core.ITronChainBase;
import org.tron.core.exception.AccountResourceInsufficientException;
import org.tron.core.exception.BadBlockException;
import org.tron.core.exception.BadItemException;
import org.tron.core.exception.BadNumberBlockException;
import org.tron.core.exception.BalanceInsufficientException;
import org.tron.core.exception.ContractExeException;
import org.tron.core.exception.ContractSizeNotEqualToOneException;
import org.tron.core.exception.ContractValidateException;
import org.tron.core.exception.DupTransactionException;
import org.tron.core.exception.HeaderNotFound;
import org.tron.core.exception.HighFreqException;
import org.tron.core.exception.ItemNotFoundException;
import org.tron.core.exception.NonCommonBlockException;
import org.tron.core.exception.OutOfSlotTimeException;
import org.tron.core.exception.ReceiptException;
import org.tron.core.exception.TaposException;
import org.tron.core.exception.TooBigTransactionException;
import org.tron.core.exception.TransactionExpirationException;
import org.tron.core.exception.TransactionTraceException;
import org.tron.core.exception.UnLinkedBlockException;
import org.tron.core.exception.UnsupportVMException;
import org.tron.core.exception.ValidateScheduleException;
import org.tron.core.exception.ValidateSignatureException;
import org.tron.core.witness.ProposalController;
import org.tron.core.witness.WitnessController;
import org.tron.protos.Protocol.AccountType;
import org.tron.protos.Protocol.Block;
import org.tron.protos.Protocol.Transaction;
@Slf4j
@Component
public class Manager {
// db store
@Autowired
private AccountStore accountStore;
@Autowired
private TransactionStore transactionStore;
@Autowired
private BlockStore blockStore;
@Autowired
private WitnessStore witnessStore;
@Autowired
private AssetIssueStore assetIssueStore;
@Autowired
private DynamicPropertiesStore dynamicPropertiesStore;
@Autowired
private BlockIndexStore blockIndexStore;
@Autowired
private AccountIdIndexStore accountIdIndexStore;
@Autowired
private WitnessScheduleStore witnessScheduleStore;
@Autowired
private RecentBlockStore recentBlockStore;
@Autowired
private VotesStore votesStore;
@Autowired
private ProposalStore proposalStore;
@Autowired
private ExchangeStore exchangeStore;
@Autowired
private TransactionHistoryStore transactionHistoryStore;
@Autowired
private CodeStore codeStore;
@Autowired
private ContractStore contractStore;
@Autowired
@Getter
private StorageRowStore storageRowStore;
// for network
@Autowired
private PeersStore peersStore;
@Autowired
private KhaosDatabase khaosDb;
private BlockCapsule genesisBlock;
@Getter
@Autowired
private RevokingDatabase revokingStore;
@Getter
private SessionOptional session = SessionOptional.instance();
@Getter
@Setter
private boolean isSyncMode;
@Getter
@Setter
private String netType;
@Getter
@Setter
private WitnessController witnessController;
@Getter
@Setter
private ProposalController proposalController;
private ExecutorService validateSignService;
private Thread repushThread;
private boolean isRunRepushThread = true;
@Getter
private Cache<Sha256Hash, Boolean> transactionIdCache = CacheBuilder
.newBuilder().maximumSize(100_000).recordStats().build();
@Getter
@Autowired
private ForkController forkController;
public WitnessStore getWitnessStore() {
return this.witnessStore;
}
private void setWitnessStore(final WitnessStore witnessStore) {
this.witnessStore = witnessStore;
}
public DynamicPropertiesStore getDynamicPropertiesStore() {
return this.dynamicPropertiesStore;
}
public void setDynamicPropertiesStore(final DynamicPropertiesStore dynamicPropertiesStore) {
this.dynamicPropertiesStore = dynamicPropertiesStore;
}
public WitnessScheduleStore getWitnessScheduleStore() {
return this.witnessScheduleStore;
}
public void setWitnessScheduleStore(final WitnessScheduleStore witnessScheduleStore) {
this.witnessScheduleStore = witnessScheduleStore;
}
public CodeStore getCodeStore() {
return codeStore;
}
public ContractStore getContractStore() {
return contractStore;
}
public VotesStore getVotesStore() {
return this.votesStore;
}
public ProposalStore getProposalStore() {
return this.proposalStore;
}
public ExchangeStore getExchangeStore() {
return this.exchangeStore;
}
public List<TransactionCapsule> getPendingTransactions() {
return this.pendingTransactions;
}
public List<TransactionCapsule> getPoppedTransactions() {
return this.popedTransactions;
}
public BlockingQueue<TransactionCapsule> getRepushTransactions() {
return repushTransactions;
}
// transactions cache
private List<TransactionCapsule> pendingTransactions;
// transactions popped
private List<TransactionCapsule> popedTransactions =
Collections.synchronizedList(Lists.newArrayList());
// the capacity is equal to Integer.MAX_VALUE default
private BlockingQueue<TransactionCapsule> repushTransactions;
// for test only
public List<ByteString> getWitnesses() {
return witnessController.getActiveWitnesses();
}
// for test only
public void addWitness(final ByteString address) {
List<ByteString> witnessAddresses = witnessController.getActiveWitnesses();
witnessAddresses.add(address);
witnessController.setActiveWitnesses(witnessAddresses);
}
public BlockCapsule getHead() throws HeaderNotFound {
List<BlockCapsule> blocks = getBlockStore().getBlockByLatestNum(1);
if (CollectionUtils.isNotEmpty(blocks)) {
return blocks.get(0);
} else {
logger.info("Header block Not Found");
throw new HeaderNotFound("Header block Not Found");
}
}
public synchronized BlockId getHeadBlockId() {
return new BlockId(
getDynamicPropertiesStore().getLatestBlockHeaderHash(),
getDynamicPropertiesStore().getLatestBlockHeaderNumber());
}
public long getHeadBlockNum() {
return getDynamicPropertiesStore().getLatestBlockHeaderNumber();
}
public long getHeadBlockTimeStamp() {
return getDynamicPropertiesStore().getLatestBlockHeaderTimestamp();
}
// public PeersStore getPeersStore() {
// return peersStore;
// }
//
// public void setPeersStore(PeersStore peersStore) {
// this.peersStore = peersStore;
// }
//
// public Node getHomeNode() {
// final Args args = Args.getInstance();
// Set<Node> nodes = this.peersStore.get("home".getBytes());
// if (nodes.size() > 0) {
// return nodes.stream().findFirst().get();
// } else {
// Node node =
// new Node(new ECKey().getNodeId(), args.getNodeExternalIp(), args.getNodeListenPort());
// nodes.add(node);
// this.peersStore.put("home".getBytes(), nodes);
// return node;
// }
// }
public void clearAndWriteNeighbours(Set<Node> nodes) {
this.peersStore.put("neighbours".getBytes(), nodes);
}
public Set<Node> readNeighbours() {
return this.peersStore.get("neighbours".getBytes());
}
/**
* Cycle thread to repush Transactions
*/
private Runnable repushLoop =
() -> {
while (isRunRepushThread) {
try {
TransactionCapsule tx = this.getRepushTransactions().poll(1, TimeUnit.SECONDS);
if (tx != null) {
this.rePush(tx);
}
} catch (InterruptedException ex) {
logger.error(ex.getMessage());
Thread.currentThread().interrupt();
} catch (Exception ex) {
logger.error("unknown exception happened in witness loop", ex);
} catch (Throwable throwable) {
logger.error("unknown throwable happened in witness loop", throwable);
}
}
};
public void stopRepushThread() {
isRunRepushThread = false;
}
@PostConstruct
public void init() {
revokingStore.disable();
revokingStore.check();
this.setWitnessController(WitnessController.createInstance(this));
this.setProposalController(ProposalController.createInstance(this));
this.pendingTransactions = Collections.synchronizedList(Lists.newArrayList());
this.repushTransactions = new LinkedBlockingQueue<>();
this.initGenesis();
try {
this.khaosDb.start(getBlockById(getDynamicPropertiesStore().getLatestBlockHeaderHash()));
} catch (ItemNotFoundException e) {
logger.error(
"Can not find Dynamic highest block from DB! \nnumber={} \nhash={}",
getDynamicPropertiesStore().getLatestBlockHeaderNumber(),
getDynamicPropertiesStore().getLatestBlockHeaderHash());
logger.error(
"Please delete database directory({}) and restart",
Args.getInstance().getOutputDirectory());
System.exit(1);
} catch (BadItemException e) {
e.printStackTrace();
logger.error("DB data broken!");
logger.error(
"Please delete database directory({}) and restart",
Args.getInstance().getOutputDirectory());
System.exit(1);
}
forkController.init(this);
revokingStore.enable();
// this.codeStore = CodeStore.create("code");
// this.contractStore = ContractStore.create("contract");
// this.storageStore = StorageStore.create("storage");
validateSignService = Executors
.newFixedThreadPool(Args.getInstance().getValidateSignThreadNum());
repushThread = new Thread(repushLoop);
repushThread.start();
}
public BlockId getGenesisBlockId() {
return this.genesisBlock.getBlockId();
}
public BlockCapsule getGenesisBlock() {
return genesisBlock;
}
/**
* init genesis block.
*/
public void initGenesis() {
this.genesisBlock = BlockUtil.newGenesisBlockCapsule();
if (this.containBlock(this.genesisBlock.getBlockId())) {
Args.getInstance().setChainId(this.genesisBlock.getBlockId().toString());
} else {
if (this.hasBlocks()) {
logger.error(
"genesis block modify, please delete database directory({}) and restart",
Args.getInstance().getOutputDirectory());
System.exit(1);
} else {
logger.info("create genesis block");
Args.getInstance().setChainId(this.genesisBlock.getBlockId().toString());
// this.pushBlock(this.genesisBlock);
blockStore.put(this.genesisBlock.getBlockId().getBytes(), this.genesisBlock);
this.blockIndexStore.put(this.genesisBlock.getBlockId());
logger.info("save block: " + this.genesisBlock);
// init DynamicPropertiesStore
this.dynamicPropertiesStore.saveLatestBlockHeaderNumber(0);
this.dynamicPropertiesStore.saveLatestBlockHeaderHash(
this.genesisBlock.getBlockId().getByteString());
this.dynamicPropertiesStore.saveLatestBlockHeaderTimestamp(
this.genesisBlock.getTimeStamp());
this.initAccount();
this.initWitness();
this.witnessController.initWits();
this.khaosDb.start(genesisBlock);
this.updateRecentBlock(genesisBlock);
}
}
}
/**
* save account into database.
*/
public void initAccount() {
final Args args = Args.getInstance();
final GenesisBlock genesisBlockArg = args.getGenesisBlock();
genesisBlockArg
.getAssets()
.forEach(
account -> {
account.setAccountType("Normal"); // to be set in conf
final AccountCapsule accountCapsule =
new AccountCapsule(
account.getAccountName(),
ByteString.copyFrom(account.getAddress()),
account.getAccountType(),
account.getBalance());
this.accountStore.put(account.getAddress(), accountCapsule);
this.accountIdIndexStore.put(accountCapsule);
});
}
/**
* save witnesses into database.
*/
private void initWitness() {
final Args args = Args.getInstance();
final GenesisBlock genesisBlockArg = args.getGenesisBlock();
genesisBlockArg
.getWitnesses()
.forEach(
key -> {
byte[] keyAddress = key.getAddress();
ByteString address = ByteString.copyFrom(keyAddress);
final AccountCapsule accountCapsule;
if (!this.accountStore.has(keyAddress)) {
accountCapsule = new AccountCapsule(ByteString.EMPTY,
address, AccountType.AssetIssue, 0L);
} else {
accountCapsule = this.accountStore.getUnchecked(keyAddress);
}
accountCapsule.setIsWitness(true);
this.accountStore.put(keyAddress, accountCapsule);
final WitnessCapsule witnessCapsule =
new WitnessCapsule(address, key.getVoteCount(), key.getUrl());
witnessCapsule.setIsJobs(true);
this.witnessStore.put(keyAddress, witnessCapsule);
});
}
public AccountStore getAccountStore() {
return this.accountStore;
}
public void adjustBalance(byte[] accountAddress, long amount)
throws BalanceInsufficientException {
AccountCapsule account = getAccountStore().getUnchecked(accountAddress);
adjustBalance(account, amount);
}
/**
* judge balance.
*/
public void adjustBalance(AccountCapsule account, long amount)
throws BalanceInsufficientException {
long balance = account.getBalance();
if (amount == 0) {
return;
}
if (amount < 0 && balance < -amount) {
throw new BalanceInsufficientException(
StringUtil.createReadableString(account.createDbKey()) + " insufficient balance");
}
account.setBalance(Math.addExact(balance, amount));
this.getAccountStore().put(account.getAddress().toByteArray(), account);
}
public void adjustAllowance(byte[] accountAddress, long amount)
throws BalanceInsufficientException {
AccountCapsule account = getAccountStore().getUnchecked(accountAddress);
long allowance = account.getAllowance();
if (amount == 0) {
return;
}
if (amount < 0 && allowance < -amount) {
throw new BalanceInsufficientException(
StringUtil.createReadableString(accountAddress) + " insufficient balance");
}
account.setAllowance(allowance + amount);
this.getAccountStore().put(account.createDbKey(), account);
}
void validateTapos(TransactionCapsule transactionCapsule) throws TaposException {
byte[] refBlockHash = transactionCapsule.getInstance()
.getRawData().getRefBlockHash().toByteArray();
byte[] refBlockNumBytes = transactionCapsule.getInstance()
.getRawData().getRefBlockBytes().toByteArray();
try {
byte[] blockHash = this.recentBlockStore.get(refBlockNumBytes).getData();
if (Arrays.equals(blockHash, refBlockHash)) {
return;
} else {
String str = String.format(
"Tapos failed, different block hash, %s, %s , recent block %s, solid block %s head block %s",
ByteArray.toLong(refBlockNumBytes), Hex.toHexString(refBlockHash),
Hex.toHexString(blockHash),
getSolidBlockId().getString(), getHeadBlockId().getString()).toString();
logger.info(str);
throw new TaposException(str);
}
} catch (ItemNotFoundException e) {
String str = String.
format("Tapos failed, block not found, ref block %s, %s , solid block %s head block %s",
ByteArray.toLong(refBlockNumBytes), Hex.toHexString(refBlockHash),
getSolidBlockId().getString(), getHeadBlockId().getString()).toString();
logger.info(str);
throw new TaposException(str);
}
}
void validateCommon(TransactionCapsule transactionCapsule)
throws TransactionExpirationException, TooBigTransactionException {
if (transactionCapsule.getData().length > Constant.TRANSACTION_MAX_BYTE_SIZE) {
throw new TooBigTransactionException(
"too big transaction, the size is " + transactionCapsule.getData().length + " bytes");
}
long transactionExpiration = transactionCapsule.getExpiration();
long headBlockTime = getHeadBlockTimeStamp();
if (transactionExpiration <= headBlockTime ||
transactionExpiration > headBlockTime + Constant.MAXIMUM_TIME_UNTIL_EXPIRATION) {
throw new TransactionExpirationException(
"transaction expiration, transaction expiration time is " + transactionExpiration
+ ", but headBlockTime is " + headBlockTime);
}
}
void validateDup(TransactionCapsule transactionCapsule) throws DupTransactionException {
if (getTransactionStore().getUnchecked(transactionCapsule.getTransactionId().getBytes())
!= null) {
logger.debug(ByteArray.toHexString(transactionCapsule.getTransactionId().getBytes()));
throw new DupTransactionException("dup trans");
}
}
/**
* push transaction into pending.
*/
public boolean pushTransaction(final TransactionCapsule trx)
throws ValidateSignatureException, ContractValidateException, ContractExeException,
AccountResourceInsufficientException, DupTransactionException, TaposException,
TooBigTransactionException, TransactionExpirationException, ReceiptException,
TransactionTraceException, OutOfSlotTimeException, UnsupportVMException {
if (!trx.validateSignature()) {
throw new ValidateSignatureException("trans sig validate failed");
}
//validateFreq(trx);
synchronized (this) {
if (!session.valid()) {
session.setValue(revokingStore.buildSession());
}
try (ISession tmpSession = revokingStore.buildSession()) {
processTransaction(trx, null);
pendingTransactions.add(trx);
tmpSession.merge();
}
}
return true;
}
public void consumeBandwidth(TransactionCapsule trx, TransactionResultCapsule ret,
TransactionTrace trace)
throws ContractValidateException, AccountResourceInsufficientException {
BandwidthProcessor processor = new BandwidthProcessor(this);
processor.consume(trx, ret, trace);
}
public void consumeEnergy(TransactionCapsule trx, TransactionResultCapsule ret,
TransactionTrace trace)
throws ContractValidateException, AccountResourceInsufficientException {
EnergyProcessor processor = new EnergyProcessor(this);
processor.consume(trx, ret, trace);
}
@Deprecated
private void validateFreq(TransactionCapsule trx) throws HighFreqException {
List<org.tron.protos.Protocol.Transaction.Contract> contracts =
trx.getInstance().getRawData().getContractList();
for (Transaction.Contract contract : contracts) {
if (contract.getType() == TransferContract || contract.getType() == TransferAssetContract) {
byte[] address = TransactionCapsule.getOwner(contract);
AccountCapsule accountCapsule = this.getAccountStore().getUnchecked(address);
if (accountCapsule == null) {
throw new HighFreqException("account not exists");
}
long balance = accountCapsule.getBalance();
long latestOperationTime = accountCapsule.getLatestOperationTime();
if (latestOperationTime != 0) {
doValidateFreq(balance, 0, latestOperationTime);
}
accountCapsule.setLatestOperationTime(Time.getCurrentMillis());
this.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule);
}
}
}
@Deprecated
private void doValidateFreq(long balance, int transNumber, long latestOperationTime)
throws HighFreqException {
long now = Time.getCurrentMillis();
// todo: avoid ddos, design more smoothly formula later.
if (balance < 1000000 * 1000) {
if (now - latestOperationTime < 5 * 60 * 1000) {
throw new HighFreqException("try later");
}
}
}
/**
* when switch fork need erase blocks on fork branch.
*/
public void eraseBlock() {
session.reset();
try {
BlockCapsule oldHeadBlock = getBlockById(
getDynamicPropertiesStore().getLatestBlockHeaderHash());
logger.info("begin to erase block:" + oldHeadBlock);
khaosDb.pop();
revokingStore.pop();
logger.info("end to erase block:" + oldHeadBlock);
popedTransactions.addAll(oldHeadBlock.getTransactions());
// todo: need add ??
// repushTransactions.addAll(oldHeadBlock.getTransactions());
//
} catch (ItemNotFoundException | BadItemException e) {
logger.warn(e.getMessage(), e);
}
}
private void applyBlock(BlockCapsule block) throws ContractValidateException,
ContractExeException, ValidateSignatureException, AccountResourceInsufficientException,
TransactionExpirationException, TooBigTransactionException, DupTransactionException, ReceiptException,
TaposException, ValidateScheduleException, TransactionTraceException, OutOfSlotTimeException,
UnsupportVMException {
processBlock(block);
this.blockStore.put(block.getBlockId().getBytes(), block);
this.blockIndexStore.put(block.getBlockId());
updateFork();
}
private void switchFork(BlockCapsule newHead)
throws ValidateSignatureException, ContractValidateException, ContractExeException,
ValidateScheduleException, AccountResourceInsufficientException, TaposException,
TooBigTransactionException, DupTransactionException, TransactionExpirationException,
NonCommonBlockException, ReceiptException, TransactionTraceException, OutOfSlotTimeException,
UnsupportVMException {
Pair<LinkedList<KhaosBlock>, LinkedList<KhaosBlock>> binaryTree;
try {
binaryTree =
khaosDb.getBranch(
newHead.getBlockId(), getDynamicPropertiesStore().getLatestBlockHeaderHash());
} catch (NonCommonBlockException e) {
logger.info(
"there is not the most recent common ancestor, need to remove all blocks in the fork chain.");
BlockCapsule tmp = newHead;
while (tmp != null) {
khaosDb.removeBlk(tmp.getBlockId());
tmp = khaosDb.getBlock(tmp.getParentHash());
}
throw e;
}
if (CollectionUtils.isNotEmpty(binaryTree.getValue())) {
while (!getDynamicPropertiesStore()
.getLatestBlockHeaderHash()
.equals(binaryTree.getValue().peekLast().getParentHash())) {
eraseBlock();
}
}
if (CollectionUtils.isNotEmpty(binaryTree.getKey())) {
List<KhaosBlock> first = new ArrayList<>(binaryTree.getKey());
Collections.reverse(first);
for (KhaosBlock item : first) {
Exception exception = null;
// todo process the exception carefully later
try (ISession tmpSession = revokingStore.buildSession()) {
applyBlock(item.getBlk());
tmpSession.commit();
} catch (AccountResourceInsufficientException
| ValidateSignatureException
| ContractValidateException
| ContractExeException
| TaposException
| DupTransactionException
| TransactionExpirationException
| TransactionTraceException
| ReceiptException
| OutOfSlotTimeException
| TooBigTransactionException
| ValidateScheduleException
| UnsupportVMException e) {
logger.warn(e.getMessage(), e);
exception = e;
throw e;
} finally {
if (exception != null) {
logger.warn("switch back because exception thrown while switching forks. " + exception
.getMessage(),
exception);
first.forEach(khaosBlock -> khaosDb.removeBlk(khaosBlock.getBlk().getBlockId()));
khaosDb.setHead(binaryTree.getValue().peekFirst());
while (!getDynamicPropertiesStore()
.getLatestBlockHeaderHash()
.equals(binaryTree.getValue().peekLast().getParentHash())) {
eraseBlock();
}
List<KhaosBlock> second = new ArrayList<>(binaryTree.getValue());
Collections.reverse(second);
for (KhaosBlock khaosBlock : second) {
// todo process the exception carefully later
try (ISession tmpSession = revokingStore.buildSession()) {
applyBlock(khaosBlock.getBlk());
tmpSession.commit();
} catch (AccountResourceInsufficientException
| ValidateSignatureException
| ContractValidateException
| ContractExeException
| TaposException
| DupTransactionException
| TransactionExpirationException
| TooBigTransactionException
| ValidateScheduleException e) {
logger.warn(e.getMessage(), e);
}
}
}
}
}
}
}
// TODO: if error need to rollback.
private synchronized void filterPendingTrx(List<TransactionCapsule> listTrx) {
}
/**
* save a block.
*/
public synchronized void pushBlock(final BlockCapsule block)
throws ValidateSignatureException, ContractValidateException, ContractExeException,
UnLinkedBlockException, ValidateScheduleException, AccountResourceInsufficientException,
TaposException, TooBigTransactionException, DupTransactionException, TransactionExpirationException,
BadNumberBlockException, BadBlockException, NonCommonBlockException, ReceiptException, TransactionTraceException,
OutOfSlotTimeException, UnsupportVMException {
try (PendingManager pm = new PendingManager(this)) {
if (!block.generatedByMyself) {
if (!block.validateSignature()) {
logger.warn("The signature is not validated.");
throw new BadBlockException("The signature is not validated");
}
if (!block.calcMerkleRoot().equals(block.getMerkleRoot())) {
logger.warn(
"The merkle root doesn't match, Calc result is "
+ block.calcMerkleRoot()
+ " , the headers is "
+ block.getMerkleRoot());
throw new BadBlockException("The merkle hash is not validated");
}
}
BlockCapsule newBlock = this.khaosDb.push(block);
// DB don't need lower block
if (getDynamicPropertiesStore().getLatestBlockHeaderHash() == null) {
if (newBlock.getNum() != 0) {
return;
}
} else {
if (newBlock.getNum() <= getDynamicPropertiesStore().getLatestBlockHeaderNumber()) {
return;
}
// switch fork
if (!newBlock
.getParentHash()
.equals(getDynamicPropertiesStore().getLatestBlockHeaderHash())) {
logger.warn(
"switch fork! new head num = {}, blockid = {}",
newBlock.getNum(),
newBlock.getBlockId());
logger.warn(
"******** before switchFork ******* push block: "
+ block.getShortString()
+ ", new block:"
+ newBlock.getShortString()
+ ", dynamic head num: "
+ dynamicPropertiesStore.getLatestBlockHeaderNumber()
+ ", dynamic head hash: "
+ dynamicPropertiesStore.getLatestBlockHeaderHash()
+ ", dynamic head timestamp: "
+ dynamicPropertiesStore.getLatestBlockHeaderTimestamp()
+ ", khaosDb head: "
+ khaosDb.getHead()
+ ", khaosDb miniStore size: "
+ khaosDb.getMiniStore().size()
+ ", khaosDb unlinkMiniStore size: "
+ khaosDb.getMiniUnlinkedStore().size());
switchFork(newBlock);
logger.info("save block: " + newBlock);
logger.warn(
"******** after switchFork ******* push block: "
+ block.getShortString()
+ ", new block:"
+ newBlock.getShortString()
+ ", dynamic head num: "
+ dynamicPropertiesStore.getLatestBlockHeaderNumber()
+ ", dynamic head hash: "
+ dynamicPropertiesStore.getLatestBlockHeaderHash()
+ ", dynamic head timestamp: "
+ dynamicPropertiesStore.getLatestBlockHeaderTimestamp()
+ ", khaosDb head: "
+ khaosDb.getHead()
+ ", khaosDb miniStore size: "
+ khaosDb.getMiniStore().size()
+ ", khaosDb unlinkMiniStore size: "
+ khaosDb.getMiniUnlinkedStore().size());
return;
}
try (ISession tmpSession = revokingStore.buildSession()) {
applyBlock(newBlock);
tmpSession.commit();
} catch (Throwable throwable) {
logger.error(throwable.getMessage(), throwable);
khaosDb.removeBlk(block.getBlockId());
throw throwable;
}
}
logger.info("save block: " + newBlock);
}
}
public void updateDynamicProperties(BlockCapsule block) {
long slot = 1;
if (block.getNum() != 1) {
slot = witnessController.getSlotAtTime(block.getTimeStamp());
}
for (int i = 1; i < slot; ++i) {
if (!witnessController.getScheduledWitness(i).equals(block.getWitnessAddress())) {
WitnessCapsule w =
this.witnessStore
.getUnchecked(StringUtil.createDbKey(witnessController.getScheduledWitness(i)));
w.setTotalMissed(w.getTotalMissed() + 1);
this.witnessStore.put(w.createDbKey(), w);
logger.info(
"{} miss a block. totalMissed = {}", w.createReadableString(), w.getTotalMissed());
}
this.dynamicPropertiesStore.applyBlock(false);
}
this.dynamicPropertiesStore.applyBlock(true);
if (slot <= 0) {
logger.warn("missedBlocks [" + slot + "] is illegal");
}
logger.info("update head, num = {}", block.getNum());
this.dynamicPropertiesStore.saveLatestBlockHeaderHash(block.getBlockId().getByteString());
this.dynamicPropertiesStore.saveLatestBlockHeaderNumber(block.getNum());
this.dynamicPropertiesStore.saveLatestBlockHeaderTimestamp(block.getTimeStamp());
revokingStore.setMaxSize((int) (dynamicPropertiesStore.getLatestBlockHeaderNumber()
- dynamicPropertiesStore.getLatestSolidifiedBlockNum()
+ 1));
khaosDb.setMaxSize((int)
(dynamicPropertiesStore.getLatestBlockHeaderNumber()
- dynamicPropertiesStore.getLatestSolidifiedBlockNum()
+ 1));
}
/**
* Get the fork branch.
*/
public LinkedList<BlockId> getBlockChainHashesOnFork(final BlockId forkBlockHash)
throws NonCommonBlockException {
final Pair<LinkedList<KhaosBlock>, LinkedList<KhaosBlock>> branch =
this.khaosDb.getBranch(
getDynamicPropertiesStore().getLatestBlockHeaderHash(), forkBlockHash);
LinkedList<KhaosBlock> blockCapsules = branch.getValue();
if (blockCapsules.isEmpty()) {
logger.info("empty branch {}", forkBlockHash);
return Lists.newLinkedList();
}
LinkedList<BlockId> result = blockCapsules.stream()
.map(KhaosBlock::getBlk)
.map(BlockCapsule::getBlockId)
.collect(Collectors.toCollection(LinkedList::new));
result.add(blockCapsules.peekLast().getBlk().getParentBlockId());
return result;
}
/**
* judge id.
*
* @param blockHash blockHash
*/
public boolean containBlock(final Sha256Hash blockHash) {
try {
return this.khaosDb.containBlockInMiniStore(blockHash)
|| blockStore.get(blockHash.getBytes()) != null;
} catch (ItemNotFoundException e) {
return false;
} catch (BadItemException e) {
return false;
}
}
public boolean containBlockInMainChain(BlockId blockId) {
try {
return blockStore.get(blockId.getBytes()) != null;
} catch (ItemNotFoundException e) {
return false;
} catch (BadItemException e) {
return false;
}
}
public void setBlockReference(TransactionCapsule trans) {
byte[] headHash = getDynamicPropertiesStore().getLatestBlockHeaderHash().getBytes();
long headNum = getDynamicPropertiesStore().getLatestBlockHeaderNumber();
trans.setReference(headNum, headHash);
}
/**
* Get a BlockCapsule by id.
*/
public BlockCapsule getBlockById(final Sha256Hash hash)
throws BadItemException, ItemNotFoundException {
return this.khaosDb.containBlock(hash)
? this.khaosDb.getBlock(hash)
: blockStore.get(hash.getBytes());
}
/**
* judge has blocks.
*/
public boolean hasBlocks() {
return blockStore.iterator().hasNext() || this.khaosDb.hasData();