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
529 lines (450 loc) · 16.1 KB
/
Manager.java
File metadata and controls
529 lines (450 loc) · 16.1 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
package org.tron.core.db;
import com.carrotsearch.sizeof.RamUsageEstimator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.protobuf.ByteString;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javafx.util.Pair;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tron.common.storage.leveldb.LevelDbDataSourceImpl;
import org.tron.common.utils.ByteArray;
import org.tron.core.Sha256Hash;
import org.tron.core.actuator.Actuator;
import org.tron.core.actuator.ActuatorFactory;
import org.tron.core.capsule.AccountCapsule;
import org.tron.core.capsule.BlockCapsule;
import org.tron.core.capsule.BlockCapsule.BlockId;
import org.tron.core.capsule.TransactionCapsule;
import org.tron.core.capsule.WitnessCapsule;
import org.tron.core.capsule.utils.BlockUtil;
import org.tron.core.config.args.Args;
import org.tron.core.config.args.GenesisBlock;
import org.tron.core.config.args.InitialWitness;
import org.tron.core.exception.BalanceInsufficientException;
import org.tron.core.exception.ContractExeException;
import org.tron.core.exception.ContractValidateException;
import org.tron.core.exception.ValidateSignatureException;
import org.tron.protos.Protocol.AccountType;
public class Manager {
private static final Logger logger = LoggerFactory.getLogger("Manager");
private static final long BLOCK_INTERVAL_SEC = 1;
private static final int MAX_ACTIVE_WITNESS_NUM = 21;
private static final long TRXS_SIZE = 2_000_000; // < 2MiB
private AccountStore accountStore;
private TransactionStore transactionStore;
private BlockStore blockStore;
private UtxoStore utxoStore;
private WitnessStore witnessStore;
private DynamicPropertiesStore dynamicPropertiesStore;
private BlockCapsule genesisBlock;
private LevelDbDataSourceImpl numHashCache;
private KhaosDatabase khaosDb;
private BlockCapsule head;
public WitnessStore getWitnessStore() {
return witnessStore;
}
private void setWitnessStore(WitnessStore witnessStore) {
this.witnessStore = witnessStore;
}
public DynamicPropertiesStore getDynamicPropertiesStore() {
return dynamicPropertiesStore;
}
public void setDynamicPropertiesStore(DynamicPropertiesStore dynamicPropertiesStore) {
this.dynamicPropertiesStore = dynamicPropertiesStore;
}
public List<TransactionCapsule> getPendingTrxs() {
return pendingTrxs;
}
// transaction cache
private List<TransactionCapsule> pendingTrxs;
private List<WitnessCapsule> wits = new ArrayList<>();
// witness
public List<WitnessCapsule> getWitnesses() {
return wits;
}
public Sha256Hash getHeadBlockId() {
return Sha256Hash.wrap(this.dynamicPropertiesStore.getLatestBlockHeaderHash());
}
public long getHeadBlockNum() {
return head.getNum();
}
/**
* TODO: should get this list from Database. get witnessCapsule List.
*/
public void initialWitnessList() {
List<InitialWitness.ActiveWitness> activeWitnessList = Args.getInstance().getInitialWitness()
.getActiveWitnessList();
activeWitnessList.forEach(activeWitness -> {
wits.add(new WitnessCapsule(ByteString.copyFromUtf8(activeWitness.getPublicKey()),
activeWitness.getUrl()));
});
}
public void addWitness(WitnessCapsule witnessCapsule) {
this.wits.add(witnessCapsule);
}
public List<WitnessCapsule> getCurrentShuffledWitnesses() {
return getWitnesses();
}
/**
* get ScheduledWitness by slot.
*/
public ByteString getScheduledWitness(long slot) {
long currentSlot = blockStore.currentASlot() + slot;
if (currentSlot < 0) {
throw new RuntimeException("currentSlot should be positive.");
}
List<WitnessCapsule> currentShuffledWitnesses = getShuffledWitnesses();
if (CollectionUtils.isEmpty(currentShuffledWitnesses)) {
throw new RuntimeException("ShuffledWitnesses is null.");
}
int witnessIndex = (int) currentSlot % currentShuffledWitnesses.size();
ByteString scheduledWitness = currentShuffledWitnesses.get(witnessIndex).getAddress();
//logger.info("scheduled_witness:" + scheduledWitness.toStringUtf8() + ",slot:" + currentSlot);
return scheduledWitness;
}
public int calculateParticipationRate() {
return 100 * dynamicPropertiesStore.getBlockFilledSlots().calculateFilledSlotsCount()
/ BlockFilledSlots.SLOT_NUMBER;
}
/**
* get shuffled witnesses.
*/
public List<WitnessCapsule> getShuffledWitnesses() {
List<WitnessCapsule> shuffleWits = getWitnesses();
//Collections.shuffle(shuffleWits);
return shuffleWits;
}
/**
* all db should be init here.
*/
public void init() {
setAccountStore(AccountStore.create("account"));
setTransactionStore(TransactionStore.create("trans"));
setBlockStore(BlockStore.create("block"));
setUtxoStore(UtxoStore.create("utxo"));
setWitnessStore(WitnessStore.create("witness"));
setDynamicPropertiesStore(DynamicPropertiesStore.create("properties"));
numHashCache = new LevelDbDataSourceImpl(
Args.getInstance().getOutputDirectory(), "block" + "_NUM_HASH");
numHashCache.initDB();
khaosDb = new KhaosDatabase("block" + "_KDB");
pendingTrxs = new ArrayList<>();
initGenesis();
initHeadBlock(Sha256Hash.wrap(this.dynamicPropertiesStore.getLatestBlockHeaderHash()));
}
public BlockId getGenesisBlockId() {
return genesisBlock.getBlockId();
}
/**
* init genesis block.
*/
public void initGenesis() {
genesisBlock = BlockUtil.newGenesisBlockCapsule();
if (containBlock(genesisBlock.getBlockId())) {
Args.getInstance().setChainId(genesisBlock.getBlockId().toString());
} else {
if (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(genesisBlock.getBlockId().toString());
try {
pushBlock(genesisBlock);
} catch (ValidateSignatureException e) {
e.printStackTrace();
}
this.dynamicPropertiesStore.saveLatestBlockHeaderNumber(0);
this.dynamicPropertiesStore.saveLatestBlockHeaderHash(
genesisBlock.getBlockId().getByteString());
this.dynamicPropertiesStore.saveLatestBlockHeaderTimestamp(
genesisBlock.getTimeStamp());
initAccount();
}
}
}
/**
* save account into database.
*/
public void initAccount() {
Args args = Args.getInstance();
GenesisBlock genesisBlockArg = args.getGenesisBlock();
genesisBlockArg.getAssets().forEach(key -> {
AccountCapsule accountCapsule = new AccountCapsule(AccountType.AssetIssue,
ByteString.copyFrom(ByteArray.fromHexString(key.getAddress())),
Long.valueOf(key.getBalance()));
this.accountStore.put(key.getAddress().getBytes(), accountCapsule);
});
}
public AccountStore getAccountStore() {
return accountStore;
}
public void adjustBalance(byte[] account_address, long amount)
throws BalanceInsufficientException {
AccountCapsule account = getAccountStore().get(account_address);
long balance = account.getBalance();
if (amount == 0) {
return;
}
if (amount < 0) {
if (balance < -amount) {
throw new BalanceInsufficientException(account_address + " Insufficient");
}
}
account.setBalance(balance + amount);
getAccountStore().put(account.getAddress().toByteArray(), account);
}
/**
* push transaction into db.
*/
public boolean pushTransactions(TransactionCapsule trx)
throws ValidateSignatureException, ContractValidateException, ContractExeException {
logger.info("push transaction");
if (!trx.validateSignature()) {
throw new ValidateSignatureException("trans sig validate failed");
}
processTransaction(trx);
pendingTrxs.add(trx);
getTransactionStore().dbSource.putData(trx.getTransactionId().getBytes(), trx.getData());
return true;
}
/**
* save a block.
*/
public void pushBlock(BlockCapsule block) throws ValidateSignatureException {
khaosDb.push(block);
//todo: check block's validity
if (!block.generatedByMyself) {
if (!block.validateSignature()) {
logger.info("The siganature is not validated.");
return;
}
if (!block.calcMerklerRoot().equals(block.getMerklerRoot())) {
logger.info("The merkler root doesn't match, Calc result is " + block.calcMerklerRoot()
+ " , the headers is " + block.getMerklerRoot());
return;
}
// block
processBlock(block);
//todo: In some case it need to switch the branch
}
getBlockStore().dbSource.putData(block.getBlockId().getBytes(), block.getData());
logger.info("save block, Its ID is " + block.getBlockId() + ", Its num is " + block.getNum());
numHashCache.putData(ByteArray.fromLong(block.getNum()), block.getBlockId().getBytes());
head = khaosDb.getHead();
// blockDbDataSource.putData(blockHash, blockData);
}
/**
* Get the fork branch.
*/
public ArrayList<BlockId> getBlockChainHashesOnFork(BlockId forkBlockHash) {
Pair<ArrayList<BlockCapsule>, ArrayList<BlockCapsule>> branch =
khaosDb.getBranch(head.getBlockId(), forkBlockHash);
return branch.getValue().stream()
.map(blockCapsule -> blockCapsule.getBlockId())
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* judge id.
*
* @param blockHash blockHash
*/
public boolean containBlock(Sha256Hash blockHash) {
//TODO: check it from levelDB
return khaosDb.containBlock(blockHash)
|| getBlockStore().dbSource.getData(blockHash.getBytes()) != null;
}
/**
* find a block packed data by id.
*/
public byte[] findBlockByHash(Sha256Hash hash) {
return khaosDb.containBlock(hash) ? khaosDb.getBlock(hash).getData()
: getBlockStore().dbSource.getData(hash.getBytes());
}
/**
* Get a BlockCapsule by id.
*/
public BlockCapsule getBlockByHash(Sha256Hash hash) {
return khaosDb.containBlock(hash) ? khaosDb.getBlock(hash)
: new BlockCapsule(getBlockStore().dbSource.getData(hash.getBytes()));
}
/**
* Delete a block.
*/
public void deleteBlock(Sha256Hash blockHash) {
BlockCapsule block = getBlockByHash(blockHash);
khaosDb.removeBlk(blockHash);
getBlockStore().dbSource.deleteData(blockHash.getBytes());
numHashCache.deleteData(ByteArray.fromLong(block.getNum()));
head = khaosDb.getHead();
}
/**
* judge has blocks.
*/
public boolean hasBlocks() {
return getBlockStore().dbSource.allKeys().size() > 0 || khaosDb.hasData();
}
/**
* Process transaction.
*/
public boolean processTransaction(TransactionCapsule trxCap)
throws ValidateSignatureException, ContractExeException, ContractValidateException {
if (trxCap == null || !trxCap.validateSignature()) {
return false;
}
List<Actuator> actuatorList = ActuatorFactory.createActuator(trxCap, this);
assert actuatorList != null;
for (Actuator act : actuatorList) {
act.validate();
act.execute();
}
return true;
}
/**
* Get the block id from the number.
*/
public BlockId getBlockIdByNum(long num) {
byte[] hash = numHashCache.getData(ByteArray.fromLong(num));
return ArrayUtils.isNotEmpty(hash)
? genesisBlock.getBlockId()
: new BlockId(Sha256Hash.wrap(hash), num);
}
/**
* Get number of block by the block id.
*/
public long getBlockNumById(Sha256Hash hash) {
if (khaosDb.containBlock(hash)) {
return khaosDb.getBlock(hash).getNum();
}
//TODO: optimize here
byte[] blockByte = getBlockStore().dbSource.getData(hash.getBytes());
return ArrayUtils.isNotEmpty(blockByte) ? new BlockCapsule(blockByte).getNum() : 0;
}
public void initHeadBlock(Sha256Hash id) {
head = getBlockByHash(id);
}
/**
* Generate a block.
*/
public BlockCapsule generateBlock(WitnessCapsule witnessCapsule,
long when, byte[] privateKey)
throws ValidateSignatureException {
final long timestamp = this.dynamicPropertiesStore.getLatestBlockHeaderTimestamp();
final long number = this.dynamicPropertiesStore.getLatestBlockHeaderNumber();
final ByteString preHash = this.dynamicPropertiesStore.getLatestBlockHeaderHash();
// judge create block time
if (when < timestamp) {
throw new IllegalArgumentException("generate block timestamp is invalid.");
}
long currentTrxSize = 0;
long postponedTrxCount = 0;
BlockCapsule blockCapsule = new BlockCapsule(number + 1, preHash, when,
witnessCapsule.getAddress());
for (TransactionCapsule trx : pendingTrxs) {
currentTrxSize += RamUsageEstimator.sizeOf(trx);
// judge block size
if (currentTrxSize > TRXS_SIZE) {
postponedTrxCount++;
continue;
}
// apply transaction
try {
if (processTransaction(trx)) {
// push into block
blockCapsule.addTransaction(trx);
pendingTrxs.remove(trx);
}
} catch (ContractExeException e) {
e.printStackTrace();
} catch (ContractValidateException e) {
e.printStackTrace();
}
}
if (postponedTrxCount > 0) {
logger.info("{} transactions over the block size limit", postponedTrxCount);
}
blockCapsule.setMerklerRoot();
blockCapsule.sign(privateKey);
blockCapsule.generatedByMyself = true;
pushBlock(blockCapsule);
dynamicPropertiesStore.saveLatestBlockHeaderHash(blockCapsule.getBlockId().getByteString());
dynamicPropertiesStore.saveLatestBlockHeaderNumber(blockCapsule.getNum());
dynamicPropertiesStore.saveLatestBlockHeaderTimestamp(blockCapsule.getTimeStamp());
return blockCapsule;
}
private void setAccountStore(AccountStore accountStore) {
this.accountStore = accountStore;
}
public TransactionStore getTransactionStore() {
return transactionStore;
}
private void setTransactionStore(TransactionStore transactionStore) {
this.transactionStore = transactionStore;
}
public BlockStore getBlockStore() {
return blockStore;
}
private void setBlockStore(BlockStore blockStore) {
this.blockStore = blockStore;
}
public UtxoStore getUtxoStore() {
return utxoStore;
}
private void setUtxoStore(UtxoStore utxoStore) {
this.utxoStore = utxoStore;
}
/**
* process block.
*/
public void processBlock(BlockCapsule block) throws ValidateSignatureException {
for (TransactionCapsule transactionCapsule : block.getTransactions()) {
try {
processTransaction(transactionCapsule);
} catch (ContractExeException e) {
e.printStackTrace();
} catch (ContractValidateException e) {
e.printStackTrace();
}
}
}
/**
* update witness.
*/
public void updateWitness() {
//TODO validate maint needed
Map<ByteString, Long> countWitness = Maps.newHashMap();
List<AccountCapsule> accountList = accountStore.getAllAccounts();
accountList.forEach(account -> {
account.getVotesList().forEach(vote -> {
//TODO validate witness //active_witness
if (countWitness.containsKey(vote.getVoteAddress())) {
countWitness.put(vote.getVoteAddress(),
countWitness.get(vote.getVoteAddress()) + vote.getVoteCount());
} else {
countWitness.put(vote.getVoteAddress(), vote.getVoteCount());
}
});
});
List<WitnessCapsule> witnessCapsuleList = Lists.newArrayList();
countWitness.forEach((address, voteCount) -> {
WitnessCapsule witnessCapsule = witnessStore.getWitness(address);
if (null == witnessCapsule) {
logger.warn("winessSouece is null.address is {}", address);
}
witnessCapsule.setVoteCount(voteCount);
witnessCapsuleList.add(witnessCapsule);
witnessStore.putWitness(witnessCapsule);
});
witnessCapsuleList.sort((a, b) -> {
return (int) (a.getVoteCount() - b.getVoteCount());
});
wits = witnessCapsuleList.subList(0, MAX_ACTIVE_WITNESS_NUM);
}
}