Skip to content

Commit 24b7d5c

Browse files
committed
add runtime test.
1 parent 468db67 commit 24b7d5c

2 files changed

Lines changed: 541 additions & 0 deletions

File tree

Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
1+
/*
2+
* java-tron is free software: you can redistribute it and/or modify
3+
* it under the terms of the GNU General Public License as published by
4+
* the Free Software Foundation, either version 3 of the License, or
5+
* (at your option) any later version.
6+
*
7+
* java-tron is distributed in the hope that it will be useful,
8+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
9+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10+
* GNU General Public License for more details.
11+
*
12+
* You should have received a copy of the GNU General Public License
13+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
14+
*/
15+
16+
package org.tron.core.db;
17+
18+
import static stest.tron.wallet.common.client.utils.PublicMethed.jsonStr2Abi;
19+
20+
import com.google.protobuf.Any;
21+
import com.google.protobuf.ByteString;
22+
import java.io.File;
23+
import java.io.UnsupportedEncodingException;
24+
import java.util.regex.Matcher;
25+
import java.util.regex.Pattern;
26+
import org.junit.AfterClass;
27+
import org.junit.Assert;
28+
import org.junit.BeforeClass;
29+
import org.junit.Test;
30+
import org.spongycastle.util.encoders.Hex;
31+
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
32+
import org.tron.common.runtime.Runtime;
33+
import org.tron.common.runtime.vm.program.invoke.ProgramInvokeFactoryImpl;
34+
import org.tron.common.storage.DepositImpl;
35+
import org.tron.common.utils.FileUtil;
36+
import org.tron.core.Constant;
37+
import org.tron.core.Wallet;
38+
import org.tron.core.capsule.AccountCapsule;
39+
import org.tron.core.capsule.BlockCapsule;
40+
import org.tron.core.capsule.TransactionCapsule;
41+
import org.tron.core.config.DefaultConfig;
42+
import org.tron.core.config.args.Args;
43+
import org.tron.core.exception.AccountResourceInsufficientException;
44+
import org.tron.core.exception.ContractExeException;
45+
import org.tron.core.exception.ContractValidateException;
46+
import org.tron.core.exception.HeaderNotFound;
47+
import org.tron.core.exception.TooBigTransactionResultException;
48+
import org.tron.core.exception.TransactionTraceException;
49+
import org.tron.protos.Contract.CreateSmartContract;
50+
import org.tron.protos.Contract.TriggerSmartContract;
51+
import org.tron.protos.Protocol.AccountType;
52+
import org.tron.protos.Protocol.SmartContract;
53+
import org.tron.protos.Protocol.Transaction;
54+
import org.tron.protos.Protocol.Transaction.Contract;
55+
import org.tron.protos.Protocol.Transaction.Contract.ContractType;
56+
import org.tron.protos.Protocol.Transaction.raw;
57+
import stest.tron.wallet.common.client.Parameter.CommonConstant;
58+
import stest.tron.wallet.common.client.utils.AbiUtil;
59+
60+
public class BandWithRuntimeOutOfTimeTest {
61+
62+
public static final long totalBalance = 1000_0000_000_000L;
63+
private static String dbPath = "output_BandWithRuntimeOutOfTimeTest_test";
64+
private static String dbDirectory = "db_BandWithRuntimeOutOfTimeTest_test";
65+
private static String indexDirectory = "index_BandWithRuntimeOutOfTimeTest_test";
66+
private static AnnotationConfigApplicationContext context;
67+
private static Manager dbManager;
68+
69+
private static String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut";
70+
private String trx2ContractAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj";
71+
private static String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA";
72+
73+
static {
74+
Args.setParam(
75+
new String[]{
76+
"--output-directory", dbPath,
77+
"--storage-db-directory", dbDirectory,
78+
"--storage-index-directory", indexDirectory,
79+
"-w"
80+
},
81+
"config-test-mainnet.conf"
82+
);
83+
context = new AnnotationConfigApplicationContext(DefaultConfig.class);
84+
}
85+
86+
/**
87+
* Init data.
88+
*/
89+
@BeforeClass
90+
public static void init() {
91+
dbManager = context.getBean(Manager.class);
92+
//init energy
93+
dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647838000L);
94+
dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(10_000_000L);
95+
96+
dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(0);
97+
98+
AccountCapsule accountCapsule = new AccountCapsule(ByteString.copyFrom("owner".getBytes()),
99+
ByteString.copyFrom(Wallet.decodeFromBase58Check(OwnerAddress)), AccountType.Normal,
100+
totalBalance);
101+
102+
accountCapsule.setFrozenForEnergy(10_000_000L, 0L);
103+
dbManager.getAccountStore()
104+
.put(Wallet.decodeFromBase58Check(OwnerAddress), accountCapsule);
105+
106+
AccountCapsule accountCapsule2 = new AccountCapsule(ByteString.copyFrom("owner".getBytes()),
107+
ByteString.copyFrom(Wallet.decodeFromBase58Check(TriggerOwnerAddress)), AccountType.Normal,
108+
totalBalance);
109+
110+
accountCapsule2.setFrozenForEnergy(10_000_000L, 0L);
111+
dbManager.getAccountStore()
112+
.put(Wallet.decodeFromBase58Check(TriggerOwnerAddress), accountCapsule2);
113+
dbManager.getDynamicPropertiesStore()
114+
.saveLatestBlockHeaderTimestamp(System.currentTimeMillis() / 1000);
115+
}
116+
117+
@Test
118+
public void testSuccess() {
119+
try {
120+
byte[] contractAddress = createContract();
121+
AccountCapsule triggerOwner = dbManager.getAccountStore()
122+
.get(Wallet.decodeFromBase58Check(TriggerOwnerAddress));
123+
long energy = triggerOwner.getEnergyUsage();
124+
long balance = triggerOwner.getBalance();
125+
TriggerSmartContract triggerContract = createTriggerContract(contractAddress,
126+
"fibonacciNotify(uint256)", "100000", false,
127+
0, Wallet.decodeFromBase58Check(TriggerOwnerAddress));
128+
Transaction transaction = Transaction.newBuilder().setRawData(raw.newBuilder().addContract(
129+
Contract.newBuilder().setParameter(Any.pack(triggerContract))
130+
.setType(ContractType.TriggerSmartContract)).setFeeLimit(1000000000)).build();
131+
TransactionCapsule trxCap = new TransactionCapsule(transaction);
132+
TransactionTrace trace = new TransactionTrace(trxCap, dbManager);
133+
dbManager.consumeBandwidth(trxCap, trace);
134+
BlockCapsule blockCapsule = null;
135+
DepositImpl deposit = DepositImpl.createRoot(dbManager);
136+
Runtime runtime = new Runtime(trace, blockCapsule, deposit, new ProgramInvokeFactoryImpl());
137+
trace.init();
138+
trace.exec(runtime);
139+
trace.finalization(runtime);
140+
141+
triggerOwner = dbManager.getAccountStore()
142+
.get(Wallet.decodeFromBase58Check(TriggerOwnerAddress));
143+
energy = triggerOwner.getEnergyUsage() - energy;
144+
balance = balance - triggerOwner.getBalance();
145+
Assert.assertNotNull(runtime.getRuntimeError());
146+
Assert.assertTrue(runtime.getRuntimeError().contains(" timeout "));
147+
Assert.assertEquals(9950000, trace.getReceipt().getEnergyUsageTotal());
148+
Assert.assertEquals(50000, energy);
149+
Assert.assertEquals(990000000, balance);
150+
Assert.assertEquals(9950000 * Constant.SUN_PER_ENERGY,
151+
balance + energy * Constant.SUN_PER_ENERGY);
152+
} catch (TransactionTraceException e) {
153+
e.printStackTrace();
154+
} catch (ContractExeException e) {
155+
e.printStackTrace();
156+
} catch (ContractValidateException e) {
157+
e.printStackTrace();
158+
} catch (AccountResourceInsufficientException e) {
159+
e.printStackTrace();
160+
} catch (TooBigTransactionResultException e) {
161+
e.printStackTrace();
162+
} catch (HeaderNotFound headerNotFound) {
163+
headerNotFound.printStackTrace();
164+
}
165+
166+
}
167+
168+
private byte[] createContract()
169+
throws ContractValidateException, AccountResourceInsufficientException, TooBigTransactionResultException, HeaderNotFound, TransactionTraceException, ContractExeException {
170+
AccountCapsule owner = dbManager.getAccountStore()
171+
.get(Wallet.decodeFromBase58Check(OwnerAddress));
172+
long energy = owner.getEnergyUsage();
173+
long balance = owner.getBalance();
174+
175+
String contractName = "Fibonacci";
176+
String code = "608060405234801561001057600080fd5b506101ba806100206000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680633c7fdc701461005157806361047ff414610092575b600080fd5b34801561005d57600080fd5b5061007c600480360381019080803590602001909291905050506100d3565b6040518082815260200191505060405180910390f35b34801561009e57600080fd5b506100bd60048036038101908080359060200190929190505050610124565b6040518082815260200191505060405180910390f35b60006100de82610124565b90507f71e71a8458267085d5ab16980fd5f114d2d37f232479c245d523ce8d23ca40ed8282604051808381526020018281526020019250505060405180910390a1919050565b60008060008060008086141561013d5760009450610185565b600186141561014f5760019450610185565b600093506001925060009150600290505b85811115156101815782840191508293508192508080600101915050610160565b8194505b505050509190505600a165627a7a7230582071f3cf655137ce9dc32d3307fb879e65f3960769282e6e452a5f0023ea046ed20029";
177+
String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"number\",\"type\":\"uint256\"}],\"name\":\"fibonacciNotify\",\"outputs\":[{\"name\":\"result\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"number\",\"type\":\"uint256\"}],\"name\":\"fibonacci\",\"outputs\":[{\"name\":\"result\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"input\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"result\",\"type\":\"uint256\"}],\"name\":\"Notify\",\"type\":\"event\"}]";
178+
CreateSmartContract smartContract = createSmartContract(
179+
Wallet.decodeFromBase58Check(OwnerAddress), contractName, abi, code, 0, 100);
180+
Transaction transaction = Transaction.newBuilder().setRawData(raw.newBuilder().addContract(
181+
Contract.newBuilder().setParameter(Any.pack(smartContract))
182+
.setType(ContractType.CreateSmartContract)).setFeeLimit(1000000000)).build();
183+
TransactionCapsule trxCap = new TransactionCapsule(transaction);
184+
TransactionTrace trace = new TransactionTrace(trxCap, dbManager);
185+
dbManager.consumeBandwidth(trxCap, trace);
186+
BlockCapsule blockCapsule = null;
187+
DepositImpl deposit = DepositImpl.createRoot(dbManager);
188+
Runtime runtime = new Runtime(trace, blockCapsule, deposit, new ProgramInvokeFactoryImpl());
189+
trace.init();
190+
trace.exec(runtime);
191+
trace.finalization(runtime);
192+
owner = dbManager.getAccountStore()
193+
.get(Wallet.decodeFromBase58Check(OwnerAddress));
194+
energy = owner.getEnergyUsage() - energy;
195+
balance = balance - owner.getBalance();
196+
Assert.assertEquals(88529, trace.getReceipt().getEnergyUsageTotal());
197+
Assert.assertEquals(50000, energy);
198+
Assert.assertEquals(3852900, balance);
199+
Assert.assertEquals(88529 * 100, balance + energy * 100);
200+
if (runtime.getRuntimeError() != null) {
201+
return runtime.getResult().getContractAddress();
202+
}
203+
return runtime.getResult().getContractAddress();
204+
205+
}
206+
207+
public CreateSmartContract createSmartContract(byte[] owner, String contractName,
208+
String abiString, String code, long value, long consumeUserResourcePercent) {
209+
Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET);
210+
211+
SmartContract.ABI abi = jsonStr2Abi(abiString);
212+
if (abi == null) {
213+
return null;
214+
}
215+
byte[] codeBytes = Hex.decode(code);
216+
SmartContract.Builder builder = SmartContract.newBuilder();
217+
builder.setName(contractName);
218+
builder.setOriginAddress(ByteString.copyFrom(owner));
219+
builder.setBytecode(ByteString.copyFrom(codeBytes));
220+
builder.setAbi(abi);
221+
builder.setConsumeUserResourcePercent(consumeUserResourcePercent);
222+
if (value != 0) {
223+
builder.setCallValue(value);
224+
}
225+
CreateSmartContract contractDeployContract = CreateSmartContract.newBuilder()
226+
.setOwnerAddress(ByteString.copyFrom(owner)).setNewContract(builder.build()).build();
227+
return contractDeployContract;
228+
}
229+
230+
public TriggerSmartContract createTriggerContract(byte[] contractAddress, String method,
231+
String argsStr,
232+
Boolean isHex, long callValue, byte[] ownerAddress) {
233+
Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET);
234+
235+
byte[] owner = ownerAddress;
236+
byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex));
237+
238+
TriggerSmartContract.Builder builder = TriggerSmartContract
239+
.newBuilder();
240+
builder.setOwnerAddress(ByteString.copyFrom(owner));
241+
builder.setContractAddress(ByteString.copyFrom(contractAddress));
242+
builder.setData(ByteString.copyFrom(input));
243+
builder.setCallValue(callValue);
244+
return builder.build();
245+
}
246+
247+
/**
248+
* destroy clear data of testing.
249+
*/
250+
@AfterClass
251+
public static void destroy() {
252+
Args.clearParam();
253+
FileUtil.deleteDir(new File(dbPath));
254+
context.destroy();
255+
}
256+
257+
private static byte[] replaceLibraryAddress(String code, byte[] libraryAddress) {
258+
259+
String libraryAddressHex;
260+
try {
261+
libraryAddressHex = (new String(Hex.encode(libraryAddress), "US-ASCII")).substring(2);
262+
} catch (UnsupportedEncodingException e) {
263+
throw new RuntimeException(e); // now ignore
264+
}
265+
266+
Matcher m = Pattern.compile("__.{36}__").matcher(code);
267+
code = m.replaceAll(libraryAddressHex);
268+
return Hex.decode(code);
269+
}
270+
}

0 commit comments

Comments
 (0)