Repository navigation
Expand file tree
/
Copy pathRuntime.java
More file actions
558 lines (469 loc) · 20.6 KB
/
Copy pathRuntime.java
File metadata and controls
558 lines (469 loc) · 20.6 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
package org.tron.common.runtime;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static org.apache.commons.lang3.ArrayUtils.isEmpty;
import static org.tron.common.runtime.utils.MUtil.convertToTronAddress;
import static org.tron.common.runtime.utils.MUtil.transfer;
import static org.tron.common.runtime.vm.VMUtils.saveProgramTraceFile;
import static org.tron.common.runtime.vm.VMUtils.zipAndEncode;
import static org.tron.common.runtime.vm.program.InternalTransaction.ExecutorType.ET_NORMAL_TYPE;
import static org.tron.common.runtime.vm.program.InternalTransaction.ExecutorType.ET_PRE_TYPE;
import static org.tron.common.runtime.vm.program.InternalTransaction.ExecutorType.ET_UNKNOWN_TYPE;
import static org.tron.common.runtime.vm.program.InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE;
import static org.tron.common.runtime.vm.program.InternalTransaction.TrxType.TRX_CONTRACT_CREATION_TYPE;
import static org.tron.common.runtime.vm.program.InternalTransaction.TrxType.TRX_PRECOMPILED_TYPE;
import static org.tron.common.runtime.vm.program.InternalTransaction.TrxType.TRX_UNKNOWN_TYPE;
import com.google.protobuf.ByteString;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.spongycastle.util.encoders.Hex;
import org.tron.common.runtime.config.SystemProperties;
import org.tron.common.runtime.vm.DataWord;
import org.tron.common.runtime.vm.PrecompiledContracts;
import org.tron.common.runtime.vm.VM;
import org.tron.common.runtime.vm.program.InternalTransaction;
import org.tron.common.runtime.vm.program.InternalTransaction.ExecutorType;
import org.tron.common.runtime.vm.program.Program;
import org.tron.common.runtime.vm.program.Program.JVMStackOverFlowException;
import org.tron.common.runtime.vm.program.ProgramPrecompile;
import org.tron.common.runtime.vm.program.ProgramResult;
import org.tron.common.runtime.vm.program.invoke.ProgramInvoke;
import org.tron.common.runtime.vm.program.invoke.ProgramInvokeFactory;
import org.tron.common.storage.Deposit;
import org.tron.common.storage.DepositImpl;
import org.tron.core.Constant;
import org.tron.core.Wallet;
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.ContractCapsule;
import org.tron.core.capsule.TransactionCapsule;
import org.tron.core.config.Parameter.ChainConstant;
import org.tron.core.config.args.Args;
import org.tron.core.db.EnergyProcessor;
import org.tron.core.db.StorageMarket;
import org.tron.core.db.TransactionTrace;
import org.tron.core.exception.ContractExeException;
import org.tron.core.exception.ContractValidateException;
import org.tron.protos.Contract;
import org.tron.protos.Contract.CreateSmartContract;
import org.tron.protos.Contract.TriggerSmartContract;
import org.tron.protos.Protocol;
import org.tron.protos.Protocol.Block;
import org.tron.protos.Protocol.SmartContract;
import org.tron.protos.Protocol.SmartContract.ABI;
import org.tron.protos.Protocol.Transaction;
import org.tron.protos.Protocol.Transaction.Contract.ContractType;
import org.tron.protos.Protocol.Transaction.Result.contractResult;
@Slf4j(topic = "Runtime")
public class Runtime {
private SystemProperties config = SystemProperties.getInstance();
private Transaction trx;
private BlockCapsule blockCap = null;
private Deposit deposit;
private ProgramInvokeFactory programInvokeFactory = null;
private String runtimeError;
private EnergyProcessor energyProcessor = null;
private StorageMarket storageMarket = null;
PrecompiledContracts.PrecompiledContract precompiledContract = null;
private ProgramResult result = new ProgramResult();
private VM vm = null;
private Program program = null;
private InternalTransaction.TrxType trxType = TRX_UNKNOWN_TYPE;
private ExecutorType executorType = ET_UNKNOWN_TYPE;
//tx trace
private TransactionTrace trace;
/**
* For blockCap's trx run
*/
public Runtime(TransactionTrace trace, BlockCapsule block, Deposit deosit,
ProgramInvokeFactory programInvokeFactory) {
this.trace = trace;
this.trx = trace.getTrx().getInstance();
if (Objects.nonNull(block)) {
this.blockCap = block;
this.executorType = ET_NORMAL_TYPE;
} else {
this.blockCap = new BlockCapsule(Block.newBuilder().build());
this.executorType = ET_PRE_TYPE;
}
this.deposit = deosit;
this.programInvokeFactory = programInvokeFactory;
this.energyProcessor = new EnergyProcessor(deposit.getDbManager());
this.storageMarket = new StorageMarket(deposit.getDbManager());
Transaction.Contract.ContractType contractType = this.trx.getRawData().getContract(0).getType();
switch (contractType.getNumber()) {
case ContractType.TriggerSmartContract_VALUE:
trxType = TRX_CONTRACT_CALL_TYPE;
break;
case ContractType.CreateSmartContract_VALUE:
trxType = TRX_CONTRACT_CREATION_TYPE;
break;
default:
trxType = TRX_PRECOMPILED_TYPE;
}
}
/**
* For constant trx with latest blockCap.
*/
public Runtime(Transaction tx, BlockCapsule block, DepositImpl deposit,
ProgramInvokeFactory programInvokeFactory) {
this.trx = tx;
this.deposit = deposit;
this.programInvokeFactory = programInvokeFactory;
this.executorType = ET_PRE_TYPE;
this.blockCap = block;
this.energyProcessor = new EnergyProcessor(deposit.getDbManager());
this.storageMarket = new StorageMarket(deposit.getDbManager());
Transaction.Contract.ContractType contractType = tx.getRawData().getContract(0).getType();
switch (contractType.getNumber()) {
case Transaction.Contract.ContractType.TriggerSmartContract_VALUE:
trxType = TRX_CONTRACT_CALL_TYPE;
break;
case Transaction.Contract.ContractType.CreateSmartContract_VALUE:
trxType = TRX_CONTRACT_CREATION_TYPE;
break;
default:
trxType = TRX_PRECOMPILED_TYPE;
}
}
public void precompiled() throws ContractValidateException, ContractExeException {
TransactionCapsule trxCap = new TransactionCapsule(trx);
final List<Actuator> actuatorList = ActuatorFactory
.createActuator(trxCap, deposit.getDbManager());
for (Actuator act : actuatorList) {
act.validate();
act.execute(result.getRet());
}
}
public BigInteger getBlockCPULeftInUs() {
// insure blockCap is not null
BigInteger curBlockHaveElapsedCPUInUs =
BigInteger.valueOf(
1000 * (DateTime.now().getMillis() - blockCap.getInstance().getBlockHeader()
.getRawData()
.getTimestamp())); // us
BigInteger curBlockCPULimitInUs = BigInteger.valueOf((long)
(1000 * ChainConstant.BLOCK_PRODUCED_INTERVAL * 0.5
* ChainConstant.BLOCK_PRODUCED_TIME_OUT
/ 100)); // us
return curBlockCPULimitInUs.subtract(curBlockHaveElapsedCPUInUs);
}
public void execute() throws ContractValidateException, ContractExeException {
switch (trxType) {
case TRX_PRECOMPILED_TYPE:
precompiled();
break;
case TRX_CONTRACT_CREATION_TYPE:
create();
break;
case TRX_CONTRACT_CALL_TYPE:
call();
break;
default:
throw new ContractValidateException("Unknown contract type");
}
}
private long getEnergyLimit(AccountCapsule account, long feeLimit, long callValue) {
long SUN_PER_ENERGY = deposit.getDbManager().getDynamicPropertiesStore().getEnergyFee() == 0
? Constant.SUN_PER_ENERGY :
deposit.getDbManager().getDynamicPropertiesStore().getEnergyFee();
// can change the calc way
long leftEnergyFromFreeze = energyProcessor.getAccountLeftEnergyFromFreeze(account);
callValue = max(callValue, 0);
long energyFromBalance = Math
.floorDiv(max(account.getBalance() - callValue, 0), SUN_PER_ENERGY);
long energyFromFeeLimit;
long totalBalanceForEnergyFreeze = account.getAccountResource().getFrozenBalanceForEnergy()
.getFrozenBalance();
if (0 == totalBalanceForEnergyFreeze) {
energyFromFeeLimit =
feeLimit / SUN_PER_ENERGY;
} else {
long totalEnergyFromFreeze = energyProcessor
.calculateGlobalEnergyLimit(totalBalanceForEnergyFreeze);
long leftBalanceForEnergyFreeze = getEnergyFee(totalBalanceForEnergyFreeze,
leftEnergyFromFreeze,
totalEnergyFromFreeze);
if (leftBalanceForEnergyFreeze >= feeLimit) {
energyFromFeeLimit = BigInteger.valueOf(totalEnergyFromFreeze)
.multiply(BigInteger.valueOf(feeLimit))
.divide(BigInteger.valueOf(totalBalanceForEnergyFreeze)).longValueExact();
} else {
energyFromFeeLimit = Math
.addExact(leftEnergyFromFreeze,
(feeLimit - leftBalanceForEnergyFreeze) / SUN_PER_ENERGY);
}
}
return min(Math.addExact(leftEnergyFromFreeze, energyFromBalance), energyFromFeeLimit);
}
private long getEnergyLimit(AccountCapsule creator, AccountCapsule caller,
TriggerSmartContract contract, long feeLimit, long callValue) {
long callerEnergyLimit = getEnergyLimit(caller, feeLimit, callValue);
if (Arrays.equals(creator.getAddress().toByteArray(), caller.getAddress().toByteArray())) {
return callerEnergyLimit;
}
// creatorEnergyFromFreeze
long creatorEnergyLimit = energyProcessor.getAccountLeftEnergyFromFreeze(creator);
SmartContract smartContract = this.deposit
.getContract(contract.getContractAddress().toByteArray()).getInstance();
long consumeUserResourcePercent = smartContract.getConsumeUserResourcePercent();
consumeUserResourcePercent = max(0, min(consumeUserResourcePercent, 100));
if (consumeUserResourcePercent <= 0) {
return creatorEnergyLimit;
}
if (creatorEnergyLimit * consumeUserResourcePercent
>= (100 - consumeUserResourcePercent) * callerEnergyLimit) {
return Math.floorDiv(callerEnergyLimit * 100, consumeUserResourcePercent);
} else {
return Math.addExact(callerEnergyLimit, creatorEnergyLimit);
}
}
private double getThisTxCPULimitInUsRatio() {
double thisTxCPULimitInUsRatio;
if (ET_NORMAL_TYPE == executorType) {
// self witness 2
if (this.blockCap != null && blockCap.generatedByMyself &&
this.blockCap.getInstance().getBlockHeader().getWitnessSignature().isEmpty()) {
thisTxCPULimitInUsRatio = 1.0;
} else
// self witness 3, other witness 3, fullnode 2
{
if (trx.getRet(0).getContractRet() == contractResult.OUT_OF_TIME) {
thisTxCPULimitInUsRatio = Args.getInstance().getMinTimeRatio();
} else {
thisTxCPULimitInUsRatio = Args.getInstance().getMaxTimeRatio();
}
}
} else {
// self witness 1, other witness 1, fullnode 1
thisTxCPULimitInUsRatio = 1.0;
}
return thisTxCPULimitInUsRatio;
}
/*
**/
private void create()
throws ContractValidateException {
if (!deposit.getDbManager().getDynamicPropertiesStore().supportVM()) {
throw new ContractValidateException("vm work is off, need to be opened by the committee");
}
CreateSmartContract contract = ContractCapsule.getSmartContractFromTransaction(trx);
SmartContract newSmartContract = contract.getNewContract();
byte[] code = newSmartContract.getBytecode().toByteArray();
byte[] contractAddress = Wallet.generateContractAddress(trx);
byte[] ownerAddress = contract.getOwnerAddress().toByteArray();
long percent = contract.getNewContract().getConsumeUserResourcePercent();
if (percent < 0 || percent > 100) {
throw new ContractValidateException("percent must be >= 0 and <= 100");
}
// insure the new contract address haven't exist
if (deposit.getAccount(contractAddress) != null) {
throw new ContractValidateException(
"Trying to create a contract with existing contract address: " + Wallet
.encode58Check(contractAddress));
}
newSmartContract = newSmartContract.toBuilder()
.setContractAddress(ByteString.copyFrom(contractAddress)).build();
long callValue = newSmartContract.getCallValue();
// create vm to constructor smart contract
try {
AccountCapsule creator = this.deposit
.getAccount(newSmartContract.getOriginAddress().toByteArray());
// if (executorType == ET_NORMAL_TYPE) {
// long blockENERGYLeftInUs = getBlockENERGYLeftInUs().longValueExact();
// thisTxENERGYLimitInUs = min(blockENERGYLeftInUs,
// Constant.ENERGY_LIMIT_IN_ONE_TX_OF_SMART_CONTRACT);
// } else {
// thisTxENERGYLimitInUs = Constant.ENERGY_LIMIT_IN_ONE_TX_OF_SMART_CONTRACT;
// }
long MAX_CPU_TIME_OF_ONE_TX = deposit.getDbManager().getDynamicPropertiesStore()
.getMaxCpuTimeOfOneTX() * 1000;
long thisTxCPULimitInUs = (long) (MAX_CPU_TIME_OF_ONE_TX * getThisTxCPULimitInUsRatio());
long vmStartInUs = System.nanoTime() / 1000;
long vmShouldEndInUs = vmStartInUs + thisTxCPULimitInUs;
long feeLimit = trx.getRawData().getFeeLimit();
long energyLimit = getEnergyLimit(creator, feeLimit, callValue);
byte[] ops = newSmartContract.getBytecode().toByteArray();
InternalTransaction internalTransaction = new InternalTransaction(trx);
ProgramInvoke programInvoke = programInvokeFactory
.createProgramInvoke(TRX_CONTRACT_CREATION_TYPE, executorType, trx,
blockCap.getInstance(), deposit, vmStartInUs, vmShouldEndInUs, energyLimit);
this.vm = new VM(config);
this.program = new Program(ops, programInvoke, internalTransaction, config, this.blockCap);
Program.setRootTransactionId(new TransactionCapsule(trx).getTransactionId().getBytes());
Program.resetNonce();
Program.setRootCallConstant(isCallConstant());
} catch (Exception e) {
logger.error(e.getMessage());
throw new ContractValidateException(e.getMessage());
}
program.getResult().setContractAddress(contractAddress);
deposit.createAccount(contractAddress, newSmartContract.getName(),
Protocol.AccountType.Contract);
deposit.createContract(contractAddress, new ContractCapsule(newSmartContract));
deposit.saveCode(contractAddress, ProgramPrecompile.getCode(code));
// deposit.createContractByNormalAccountIndex(ownerAddress, new BytesCapsule(contractAddress));
// transfer from callerAddress to contractAddress according to callValue
byte[] callerAddress = contract.getOwnerAddress().toByteArray();
if (callValue > 0) {
transfer(this.deposit, callerAddress, contractAddress, callValue);
}
}
/**
* **
*/
private void call()
throws ContractValidateException {
if (!deposit.getDbManager().getDynamicPropertiesStore().supportVM()) {
throw new ContractValidateException("VM work is off, need to be opened by the committee");
}
Contract.TriggerSmartContract contract = ContractCapsule.getTriggerContractFromTransaction(trx);
if (contract == null) {
return;
}
byte[] contractAddress = contract.getContractAddress().toByteArray();
byte[] code = this.deposit.getCode(contractAddress);
long callValue = contract.getCallValue();
if (isEmpty(code)) {
} else {
AccountCapsule caller = this.deposit.getAccount(contract.getOwnerAddress().toByteArray());
AccountCapsule creator = this.deposit.getAccount(
this.deposit.getContract(contractAddress).getInstance()
.getOriginAddress().toByteArray());
long MAX_CPU_TIME_OF_ONE_TX = deposit.getDbManager().getDynamicPropertiesStore()
.getMaxCpuTimeOfOneTX() * 1000;
long thisTxCPULimitInUs =
(long) (MAX_CPU_TIME_OF_ONE_TX * getThisTxCPULimitInUsRatio());
long vmStartInUs = System.nanoTime() / 1000;
long vmShouldEndInUs = vmStartInUs + thisTxCPULimitInUs;
long feeLimit = trx.getRawData().getFeeLimit();
long energyLimit;
if (isCallConstant(contractAddress)) {
energyLimit = Constant.MAX_ENERGY_IN_TX;
} else {
energyLimit = getEnergyLimit(creator, caller, contract, feeLimit, callValue);
}
ProgramInvoke programInvoke = programInvokeFactory
.createProgramInvoke(TRX_CONTRACT_CALL_TYPE, executorType, trx,
blockCap.getInstance(), deposit, vmStartInUs, vmShouldEndInUs, energyLimit);
this.vm = new VM(config);
InternalTransaction internalTransaction = new InternalTransaction(trx);
this.program = new Program(null, code, programInvoke, internalTransaction, config,
this.blockCap);
Program.setRootTransactionId(new TransactionCapsule(trx).getTransactionId().getBytes());
Program.resetNonce();
Program.setRootCallConstant(isCallConstant());
}
program.getResult().setContractAddress(contractAddress);
//transfer from callerAddress to targetAddress according to callValue
byte[] callerAddress = contract.getOwnerAddress().toByteArray();
if (callValue > 0) {
transfer(this.deposit, callerAddress, contractAddress, callValue);
}
}
public void go() {
try {
if (vm != null) {
vm.play(program);
program.getResult().setRet(result.getRet());
result = program.getResult();
if (isCallConstant()) {
long callValue = TransactionCapsule.getCallValue(trx.getRawData().getContract(0));
if (callValue > 0) {
runtimeError = "constant cannot set call value.";
}
return;
}
if (result.getException() != null || result.isRevert()) {
result.getDeleteAccounts().clear();
result.getLogInfoList().clear();
result.resetFutureRefund();
if (result.getException() != null) {
program.spendAllEnergy();
runtimeError = result.getException().getMessage();
throw result.getException();
} else {
runtimeError = "REVERT opcode executed";
}
} else {
deposit.commit();
}
} else {
deposit.commit();
}
} catch (JVMStackOverFlowException e) {
result.setException(e);
runtimeError = result.getException().getMessage();
logger.error("runtime error is :{}", result.getException().getMessage());
} catch (Throwable e) {
if (Objects.isNull(result.getException())) {
logger.error(e.getMessage(), e);
result.setException(new RuntimeException("Unknown Throwable"));
}
if (StringUtils.isEmpty(runtimeError)) {
runtimeError = result.getException().getMessage();
}
logger.error("runtime error is :{}", result.getException().getMessage());
}
trace.setBill(result.getEnergyUsed());
}
private long getEnergyFee(long callerEnergyUsage, long callerEnergyFrozen,
long callerEnergyTotal) {
if (callerEnergyTotal <= 0) {
return 0;
}
return BigInteger.valueOf(callerEnergyFrozen).multiply(BigInteger.valueOf(callerEnergyUsage))
.divide(BigInteger.valueOf(callerEnergyTotal)).longValueExact();
}
public boolean isCallConstant() throws ContractValidateException {
TriggerSmartContract triggerContractFromTransaction = ContractCapsule
.getTriggerContractFromTransaction(trx);
if (TRX_CONTRACT_CALL_TYPE.equals(trxType)) {
ABI abi = deposit
.getContract(triggerContractFromTransaction.getContractAddress().toByteArray())
.getInstance().getAbi();
if (Wallet.isConstant(abi, triggerContractFromTransaction)) {
return true;
}
}
return false;
}
private boolean isCallConstant(byte[] address) throws ContractValidateException {
if (TRX_CONTRACT_CALL_TYPE.equals(trxType)) {
ABI abi = deposit.getContract(address).getInstance().getAbi();
if (Wallet.isConstant(abi, ContractCapsule.getTriggerContractFromTransaction(trx))) {
return true;
}
}
return false;
}
public void finalization() {
for (DataWord contract : result.getDeleteAccounts()) {
deposit.deleteContract(convertToTronAddress((contract.getLast20Bytes())));
}
if (config.vmTrace() && program != null && result != null) {
String trace = program.getTrace()
.result(result.getHReturn())
.error(result.getException())
.toString();
if (config.vmTraceCompressed()) {
trace = zipAndEncode(trace);
}
String txHash = Hex.toHexString(new InternalTransaction(trx).getHash());
saveProgramTraceFile(config, txHash, trace);
}
}
public ProgramResult getResult() {
return result;
}
public String getRuntimeError() {
return runtimeError;
}
}