/
StandaloneBlockchain.java
453 lines (392 loc) · 18.7 KB
/
StandaloneBlockchain.java
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
package org.aion.zero.impl;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.aion.base.db.IContractDetails;
import org.aion.base.db.IPruneConfig;
import org.aion.base.db.IRepositoryCache;
import org.aion.base.db.IRepositoryConfig;
import org.aion.base.type.AionAddress;
import org.aion.base.type.Hash256;
import org.aion.base.util.ByteArrayWrapper;
import org.aion.crypto.ECKey;
import org.aion.crypto.ECKeyFac;
import org.aion.crypto.HashUtil;
import org.aion.db.impl.DBVendor;
import org.aion.db.impl.DatabaseFactory;
import org.aion.mcf.config.CfgPrune;
import org.aion.mcf.core.AccountState;
import org.aion.mcf.core.ImportResult;
import org.aion.mcf.valid.BlockHeaderValidator;
import org.aion.mcf.vm.types.DataWord;
import org.aion.precompiled.ContractFactory;
import org.aion.vm.api.interfaces.Address;
import org.aion.zero.exceptions.HeaderStructureException;
import org.aion.zero.impl.blockchain.ChainConfiguration;
import org.aion.zero.impl.core.energy.AbstractEnergyStrategyLimit;
import org.aion.zero.impl.core.energy.TargetStrategy;
import org.aion.zero.impl.db.AionRepositoryImpl;
import org.aion.zero.impl.db.ContractDetailsAion;
import org.aion.zero.impl.types.AionBlock;
import org.aion.zero.impl.types.AionBlockSummary;
import org.aion.zero.impl.valid.AionExtraDataRule;
import org.aion.zero.impl.valid.AionHeaderVersionRule;
import org.aion.zero.impl.valid.EnergyConsumedRule;
import org.aion.zero.types.A0BlockHeader;
import org.apache.commons.lang3.tuple.Pair;
/**
* Used mainly for debugging and testing purposes, provides codepaths for easy setup, into standard
* configurations that a user might expected, and handles any non-intuitive setup that the
* blockchain may require.
*/
public class StandaloneBlockchain extends AionBlockchainImpl {
public AionGenesis genesis;
private static IRepositoryConfig repoConfig =
new IRepositoryConfig() {
@Override
public String getDbPath() {
return "";
}
@Override
public IPruneConfig getPruneConfig() {
return new CfgPrune(false);
}
@Override
public IContractDetails contractDetailsImpl() {
return ContractDetailsAion.createForTesting(0, 1000000).getDetails();
}
@Override
public Properties getDatabaseConfig(String db_name) {
Properties props = new Properties();
props.setProperty(DatabaseFactory.Props.DB_TYPE, DBVendor.MOCKDB.toValue());
props.setProperty(DatabaseFactory.Props.ENABLE_HEAP_CACHE, "false");
return props;
}
};
protected StandaloneBlockchain(final A0BCConfig config, final ChainConfiguration chainConfig) {
super(config, AionRepositoryImpl.createForTesting(repoConfig), chainConfig);
}
protected StandaloneBlockchain(
final A0BCConfig config,
final ChainConfiguration chainConfig,
IRepositoryConfig repoConfig) {
super(config, AionRepositoryImpl.createForTesting(repoConfig), chainConfig);
}
public void setGenesis(AionGenesis genesis) {
this.genesis = genesis;
}
public AionGenesis getGenesis() {
return this.genesis;
}
public void loadJSON(String json) {}
public BlockHeaderValidator getBlockHeaderValidator() {
return this.chainConfiguration.createBlockHeaderValidator();
}
public static class Bundle {
public final List<ECKey> privateKeys;
public final StandaloneBlockchain bc;
public Bundle(List<ECKey> privateKeys, StandaloneBlockchain bc) {
this.privateKeys = privateKeys;
this.bc = bc;
}
}
public static class Builder {
private A0BCConfig a0Config;
// note that this parameter is usually not injected into the blockchain
// it remains here so we can replace the default validator
private ChainConfiguration configuration;
private List<ECKey> defaultKeys = new ArrayList<>();
private Map<ByteArrayWrapper, AccountState> initialState = new HashMap<>();
private IRepositoryConfig repoConfig;
public static final int INITIAL_ACC_LEN = 10;
public static final BigInteger DEFAULT_BALANCE =
new BigInteger("1000000000000000000000000");
/**
* The type of validator selected for the blockchain, a "full" validator validates blocks as
* if they were broadcasted from the network. Therefore the header validator will require a
* valid equiHash solution.
*
* <p>{@code validatorType -> (full|simple)}
*/
String validatorType;
public Builder withValidatorConfiguration(String type) {
this.validatorType = type;
return this;
}
public Builder withDefaultAccounts() {
for (int i = 0; i < INITIAL_ACC_LEN; i++) {
ECKey pk = ECKeyFac.inst().create();
this.defaultKeys.add(pk);
initialState.put(
new ByteArrayWrapper(pk.getAddress()),
new AccountState(BigInteger.ZERO, DEFAULT_BALANCE));
}
return this;
}
public Builder withDefaultAccounts(List<ECKey> defaultAccounts) {
this.defaultKeys.addAll(defaultAccounts);
this.defaultKeys.forEach(
k ->
initialState.put(
new ByteArrayWrapper(k.getAddress()),
new AccountState(BigInteger.ZERO, DEFAULT_BALANCE)));
return this;
}
public Builder withRepoConfig(IRepositoryConfig config) {
this.repoConfig = config;
return this;
}
public Builder withA0Config(A0BCConfig config) {
this.a0Config = config;
return this;
}
public Builder withChainConfig(ChainConfiguration chainConfig) {
if (this.validatorType != null) {
throw new IllegalArgumentException("cannot set chainConfig after setting type");
}
this.configuration = chainConfig;
return this;
}
public Builder withAccount(ByteArrayWrapper publicKey, AccountState accState) {
initialState.put(publicKey, accState);
return this;
}
private IRepositoryConfig generateRepositoryConfig() {
return new IRepositoryConfig() {
@Override
public String getDbPath() {
return "";
}
@Override
public IPruneConfig getPruneConfig() {
return new CfgPrune(false);
}
@Override
public IContractDetails contractDetailsImpl() {
return ContractDetailsAion.createForTesting(0, 1000000).getDetails();
}
@Override
public Properties getDatabaseConfig(String db_name) {
Properties props = new Properties();
props.setProperty(DatabaseFactory.Props.DB_TYPE, DBVendor.MOCKDB.toValue());
props.setProperty(DatabaseFactory.Props.ENABLE_HEAP_CACHE, "false");
return props;
}
};
}
public Bundle build() {
this.a0Config =
this.a0Config == null
? new A0BCConfig() {
@Override
public Address getCoinbase() {
return AionAddress.ZERO_ADDRESS();
}
@Override
public byte[] getExtraData() {
return new byte[32];
}
@Override
public boolean getExitOnBlockConflict() {
return false;
}
@Override
public Address getMinerCoinbase() {
return AionAddress.ZERO_ADDRESS();
}
@Override
public int getFlushInterval() {
return 1;
}
@Override
public AbstractEnergyStrategyLimit getEnergyLimitStrategy() {
return new TargetStrategy(
configuration.getConstants().getEnergyLowerBoundLong(),
configuration
.getConstants()
.getEnergyDivisorLimitLong(),
10_000_000L);
}
@Override
public boolean isAvmEnabled() {
return false;
}
}
: this.a0Config;
if (this.configuration == null) {
if (this.validatorType == null) {
this.configuration = new ChainConfiguration();
} else if (this.validatorType.equals("full")) {
this.configuration = new ChainConfiguration();
} else if (this.validatorType.equals("simple")) {
this.configuration =
new ChainConfiguration() {
/*
* Remove the equiHash solution for the simplified
* validator this gives us the ability to connect new
* blocks without validating the solution and POW.
*
* This is good for transaction testing, but another set
* of tests need to ensure that the equihash and POW
* generated are valid.
*/
@Override
public BlockHeaderValidator<A0BlockHeader>
createBlockHeaderValidator() {
return new BlockHeaderValidator<A0BlockHeader>(
Arrays.asList(
new AionExtraDataRule(
this.constants
.getMaximumExtraDataSize()),
new EnergyConsumedRule(),
new AionHeaderVersionRule()));
}
};
} else {
throw new IllegalArgumentException("validatorType != (full|simple)");
}
}
if (this.repoConfig == null) {
this.repoConfig = generateRepositoryConfig();
}
StandaloneBlockchain bc =
new StandaloneBlockchain(this.a0Config, this.configuration, this.repoConfig);
AionGenesis.Builder genesisBuilder = new AionGenesis.Builder();
for (Map.Entry<ByteArrayWrapper, AccountState> acc : this.initialState.entrySet()) {
genesisBuilder.addPreminedAccount(AionAddress.wrap(acc.getKey()), acc.getValue());
}
AionGenesis genesis;
try {
genesis = genesisBuilder.build();
} catch (HeaderStructureException e) {
throw new RuntimeException(e);
}
bc.genesis = genesis;
IRepositoryCache track = bc.getRepository().startTracking();
track.createAccount(ContractFactory.getTotalCurrencyContractAddress());
for (Map.Entry<Integer, BigInteger> key : genesis.getNetworkBalances().entrySet()) {
track.addStorageRow(
ContractFactory.getTotalCurrencyContractAddress(),
new DataWord(key.getKey()).toWrapper(),
new DataWord(key.getValue()).toWrapper());
}
for (Address key : genesis.getPremine().keySet()) {
track.createAccount(key);
track.addBalance(key, genesis.getPremine().get(key).getBalance());
}
track.flush();
bc.getRepository().commitBlock(genesis.getHeader());
bc.getRepository().getBlockStore().saveBlock(genesis, genesis.getDifficultyBI(), true);
bc.setBestBlock(genesis);
bc.setTotalDifficulty(genesis.getDifficultyBI());
if (genesis.getCumulativeDifficulty().equals(BigInteger.ZERO)) {
// setting the object runtime value
genesis.setCumulativeDifficulty(genesis.getDifficultyBI());
}
return new Bundle(this.defaultKeys, bc);
}
}
/** for testing */
public BigInteger getCachedTotalDifficulty() {
return getCacheTD();
}
public void assertEqualTotalDifficulty() {
BigInteger tdForHash, tdCached, tdPublic;
byte[] bestBlockHash;
synchronized (this) {
bestBlockHash = getBestBlock().getHash();
tdForHash = getBlockStore().getTotalDifficultyForHash(getBestBlock().getHash());
tdCached = getCacheTD();
tdPublic = getTotalDifficulty();
}
assert (tdPublic.equals(tdForHash));
assert (tdPublic.equals(tdCached));
assert (tdForHash.equals(getTotalDifficultyByHash(new Hash256(bestBlockHash))));
}
@Override
public synchronized ImportResult tryToConnect(final AionBlock block) {
ImportResult result = tryToConnectInternal(block, System.currentTimeMillis() / 1000);
if (result == ImportResult.IMPORTED_BEST) {
BigInteger tdForHash = getBlockStore().getTotalDifficultyForHash(block.getHash());
assert (getTotalDifficulty().equals(tdForHash));
assert (getCacheTD().equals(tdForHash));
}
return result;
}
// TEMPORARY: here to support the ConsensusTest
public synchronized Pair<ImportResult, AionBlockSummary> tryToConnectAndFetchSummary(
AionBlock block) {
return tryToConnectAndFetchSummary(block, System.currentTimeMillis() / 1000);
}
/**
* @apiNote users should beware that this will cause a disconnect in the blockchain, one should
* not expect to use any block that is below {@code blockNumber}
* @apiNote as a consequence of the creation behaviour do not attempt to conduct VM bytecode
* that queries the history of the chain.
* <p>This should <i>always</i> be used first, do not attempt to use this function after a
* blockchain has already been altered in some state.
* @implNote creates a new block that does not reference any parent and adds it into the
* blockchain (note that this will cause a disconnect in the blockchain)
* @param blockNumber to be set in the blockchain
*/
public synchronized void setBlockNumber(long blockNumber) {
// cannot replace genesis
assert blockNumber > 0;
assert blockNumber > this.getBestBlock().getNumber();
// enforce that we have just created the blockchain, and have not
// altered it in any drastic fashion
assert this.getBestBlock() == this.genesis;
try {
// we also need a grandparent block to calculate difficulty
AionBlock grandParentBlock = null;
if (this.getBlockStore().getBlocksByNumber((int) blockNumber - 1).size() == 0) {
// create a grandparent block if none exists
A0BlockHeader header =
new A0BlockHeader.Builder()
.withStateRoot(this.getBestBlock().getStateRoot())
.withTxTrieRoot(HashUtil.EMPTY_TRIE_HASH)
.withReceiptTrieRoot(HashUtil.EMPTY_TRIE_HASH)
.withNumber((int) blockNumber - 1)
.withEnergyLimit(this.genesis.getNrgLimit())
.withDifficulty(this.genesis.getDifficulty())
.withTimestamp(0)
.build();
AionBlock block = new AionBlock(header, Collections.emptyList());
this.setBestBlock(block);
this.getBlockStore().saveBlock(block, this.genesis.getCumulativeDifficulty(), true);
grandParentBlock = block;
} else {
// grab the grandparent block from the database if it exists
grandParentBlock =
this.getBlockStore()
.getBlocksByNumber((int) blockNumber - 1)
.get(0)
.getKey();
}
A0BlockHeader bestHeader = this.getBestBlock().getHeader();
A0BlockHeader header =
new A0BlockHeader.Builder()
.withParentHash(grandParentBlock.getHash())
.withStateRoot(this.getBestBlock().getStateRoot())
.withTxTrieRoot(HashUtil.EMPTY_TRIE_HASH)
.withReceiptTrieRoot(HashUtil.EMPTY_TRIE_HASH)
.withDifficulty(this.getBestBlock().getDifficulty())
.withEnergyLimit(this.getBestBlock().getNrgLimit())
.withTimestamp(1)
.withNumber(blockNumber)
.build();
AionBlock block = new AionBlock(header, Collections.emptyList());
this.setBestBlock(block);
this.getBlockStore().saveBlock(block, this.genesis.getCumulativeDifficulty(), true);
} catch (Exception e) {
// any exception here should kill the tests
// rethrow as runtime
throw new RuntimeException(e);
}
}
}