forked from tronprotocol/java-tron
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockchain.java
More file actions
389 lines (317 loc) · 12.1 KB
/
Blockchain.java
File metadata and controls
389 lines (317 loc) · 12.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
/*
* java-tron is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* java-tron is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.tron.core;
import static org.tron.core.Constant.BLOCK_DB_NAME;
import static org.tron.core.Constant.LAST_HASH;
import com.alibaba.fastjson.JSON;
import com.google.common.io.ByteStreams;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tron.common.crypto.ECKey;
import org.tron.common.overlay.Net;
import org.tron.common.storage.leveldb.LevelDbDataSourceImpl;
import org.tron.common.utils.ByteArray;
import org.tron.core.capsule.BlockCapsule;
import org.tron.core.capsule.TransactionCapsule;
import org.tron.core.config.Configer;
import org.tron.core.events.BlockchainListener;
import org.tron.core.peer.Peer;
import org.tron.protos.Protocal.Block;
import org.tron.protos.Protocal.TXInput;
import org.tron.protos.Protocal.TXOutput;
import org.tron.protos.Protocal.TXOutputs;
import org.tron.protos.Protocal.Transaction;
public class Blockchain {
public static final String GENESIS_COINBASE_DATA = "0x10";
public static final Logger logger = LoggerFactory.getLogger("BlockChain");
public static String parentName = Constant.NORMAL;
private LevelDbDataSourceImpl blockDb;
private PendingState pendingState = new PendingStateImpl();
private byte[] lastHash;
private byte[] currentHash;
private List<BlockchainListener> listeners = new ArrayList<>();
/**
* create new blockchain.
*
* @param blockDb block database
*/
public Blockchain(@Named("block") LevelDbDataSourceImpl blockDb) {
this.blockDb = blockDb;
this.lastHash = blockDb.getData(LAST_HASH);
if (this.lastHash == null) {
GenesisBlockLoader genesisBlockLoader = buildGenesisBlockLoader();
List<Transaction> transactions = buildTransactionsFrom(genesisBlockLoader);
Block genesisBlock = BlockCapsule.newGenesisBlock(transactions);
this.lastHash = genesisBlock.getBlockHeader().getHash().toByteArray();
this.currentHash = this.lastHash;
persistGenesisBlockToDB(blockDb, genesisBlock);
persistLastHash(blockDb, genesisBlock);
addGenesisBlockToListeners(genesisBlock);
logger.info("new blockchain");
} else {
this.currentHash = this.lastHash;
logger.info("load blockchain");
}
}
private void addGenesisBlockToListeners(Block genesisBlock) {
listeners.stream().forEach(l -> l.addGenesisBlock(genesisBlock));
}
private void persistLastHash(@Named("block") LevelDbDataSourceImpl blockDb, Block genesisBlock) {
byte[] lastHash = genesisBlock.getBlockHeader()
.getHash()
.toByteArray();
blockDb.putData(LAST_HASH, lastHash);
}
private void persistGenesisBlockToDB(@Named("block") LevelDbDataSourceImpl blockDB,
Block genesisBlock) {
blockDB.putData(genesisBlock.getBlockHeader().getHash().toByteArray(),
genesisBlock.toByteArray());
}
private List<Transaction> buildTransactionsFrom(GenesisBlockLoader genesisBlockLoader) {
return genesisBlockLoader.getTransaction().entrySet().stream()
.map(e ->
TransactionCapsule
.newCoinbaseTransaction(e.getKey(), GENESIS_COINBASE_DATA, e.getValue())
).collect(Collectors.toList());
}
private GenesisBlockLoader buildGenesisBlockLoader() {
InputStream is = getClass().getClassLoader().getResourceAsStream("genesis.json");
String json = null;
try {
json = new String(ByteStreams.toByteArray(is));
} catch (IOException e) {
logger.warn("Fail to load genesis.json, error: {}", e);
}
return JSON.parseObject(json, GenesisBlockLoader.class);
}
/**
* Checks if the database file exists.
*
* @return boolean
*/
public static boolean dbExists() {
if (Constant.NORMAL == parentName) {
parentName = Configer.getConf(Constant.NORMAL_CONF).getString(Constant.DATABASE_DIR);
} else {
parentName = Configer.getConf(Constant.TEST_CONF).getString(Constant.DATABASE_DIR);
}
File file = new File(Paths.get(parentName, BLOCK_DB_NAME).toString());
return file.exists();
}
/**
* find transaction by id.
*
* @param id ByteString id
* @return {@link Transaction}
*/
public Transaction findTransaction(ByteString id) {
Transaction transaction = Transaction.newBuilder().build();
BlockchainIterator bi = new BlockchainIterator(this);
while (bi.hasNext()) {
Block block = bi.next();
for (Transaction tx : block.getTransactionsList()) {
String txId = ByteArray.toHexString(tx.getId().toByteArray());
String idStr = ByteArray.toHexString(id.toByteArray());
if (txId.equals(idStr)) {
transaction = tx.toBuilder().build();
return transaction;
}
}
if (block.getBlockHeader().getParentHash().isEmpty()) {
break;
}
}
return transaction;
}
public HashMap<String, TXOutputs> findUtxo() {
HashMap<String, TXOutputs> utxo = new HashMap<>();
HashMap<String, long[]> spenttxos = new HashMap<>();
BlockchainIterator bi = new BlockchainIterator(this);
while (bi.hasNext()) {
Block block = bi.next();
for (Transaction transaction : block.getTransactionsList()) {
String txid = ByteArray.toHexString(transaction.getId().toByteArray());
output:
for (int outIdx = 0; outIdx < transaction.getVoutList().size(); outIdx++) {
TXOutput out = transaction.getVout(outIdx);
if (!spenttxos.isEmpty() && spenttxos.containsKey(txid)) {
for (int i = 0; i < spenttxos.get(txid).length; i++) {
if (spenttxos.get(txid)[i] == outIdx) {
continue output;
}
}
}
TXOutputs outs = utxo.get(txid);
if (outs == null) {
outs = TXOutputs.newBuilder().build();
}
outs = outs.toBuilder().addOutputs(out).build();
utxo.put(txid, outs);
}
if (!TransactionCapsule.isCoinbaseTransaction(transaction)) {
for (TXInput in : transaction.getVinList()) {
String inTxid = ByteArray.toHexString(in.getTxID()
.toByteArray());
long[] vindexs = spenttxos.get(inTxid);
if (vindexs == null) {
vindexs = new long[0];
}
vindexs = Arrays.copyOf(vindexs, vindexs.length + 1);
vindexs[vindexs.length - 1] = in.getVout();
spenttxos.put(inTxid, vindexs);
}
}
}
}
return utxo;
}
/**
* add a block into database.
*/
public void addBlock(Block block) {
byte[] blockInDB = blockDb.getData(block.getBlockHeader().getHash().toByteArray());
if (blockInDB == null || blockInDB.length == 0) {
return;
}
persistGenesisBlockToDB(blockDb, block);
byte[] lastHash = blockDb.getData(ByteArray.fromString("lashHash"));
byte[] lastBlockData = blockDb.getData(lastHash);
try {
Block lastBlock = Block.parseFrom(lastBlockData);
if (block.getBlockHeader().getNumber() > lastBlock.getBlockHeader().getNumber()) {
blockDb.putData(ByteArray.fromString("lashHash"),
block.getBlockHeader().getHash().toByteArray());
this.lastHash = block.getBlockHeader().getHash().toByteArray();
this.currentHash = this.lastHash;
}
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
public Transaction signTransaction(Transaction transaction, ECKey myKey) {
HashMap<String, Transaction> prevTXs = new HashMap<>();
for (TXInput txInput : transaction.getVinList()) {
ByteString txId = txInput.getTxID();
Transaction prevTX = this.findTransaction(txId).toBuilder().build();
String key = ByteArray.toHexString(txId.toByteArray());
prevTXs.put(key, prevTX);
}
//transaction = TransactionCapsule.sign(transaction, myKey, prevTXs);
transaction = TransactionCapsule
.sign(transaction, myKey);//Unsupport muilty address, needn't input prevTXs
return transaction;
}
/**
* {@see org.tron.common.overlay.kafka.KafkaTest#testKafka()}
*
* @param transactions transactions
*/
public void addBlock(List<Transaction> transactions, Net net) {
// getData lastHash
byte[] lastHash = blockDb.getData(LAST_HASH);
ByteString parentHash = ByteString.copyFrom(lastHash);
// getData number
long number = BlockCapsule.getIncreaseNumber(this);
// getData difficulty
ByteString difficulty = ByteString.copyFromUtf8(Constant.DIFFICULTY);
Block block = BlockCapsule.newBlock(transactions, parentHash, difficulty,
number);
for (BlockchainListener listener : listeners) {
listener.addBlockNet(block, net);
}
}
/**
* add a block.
*/
public void addBlock(List<Transaction> transactions) {
// get lastHash
byte[] lastHash = blockDb.getData(LAST_HASH);
ByteString parentHash = ByteString.copyFrom(lastHash);
// get number
long number = BlockCapsule.getIncreaseNumber(this);
// get difficulty
ByteString difficulty = ByteString.copyFromUtf8(Constant.DIFFICULTY);
Block block = BlockCapsule.newBlock(transactions, parentHash, difficulty,
number);
for (BlockchainListener listener : listeners) {
listener.addBlock(block);
}
}
/**
* receive a block and save it into database,update caching at the same time.
*
* @param block block
* @param utxoSet utxoSet
*/
public void receiveBlock(Block block, UTXOSet utxoSet, Peer peer) {
byte[] lastHashKey = LAST_HASH;
byte[] lastHash = blockDb.getData(lastHashKey);
if (!ByteArray.toHexString(block.getBlockHeader().getParentHash().toByteArray())
.equals(ByteArray.toHexString(lastHash))) {
return;
}
// save the block into the database
byte[] blockHashKey = block.getBlockHeader().getHash().toByteArray();
byte[] blockVal = block.toByteArray();
blockDb.putData(blockHashKey, blockVal);
byte[] ch = block.getBlockHeader().getHash().toByteArray();
// update lastHash
peer.getBlockchain().getBlockDB().putData(lastHashKey, ch);
this.lastHash = ch;
currentHash = ch;
System.out.println(BlockCapsule.toPrintString(block));
// update UTXO cache
utxoSet.reindex();
}
public void addListener(BlockchainListener listener) {
this.listeners.add(listener);
}
public LevelDbDataSourceImpl getBlockDB() {
return blockDb;
}
public void setBlockDB(LevelDbDataSourceImpl blockDB) {
this.blockDb = blockDB;
}
public PendingState getPendingState() {
return pendingState;
}
public void setPendingState(PendingState pendingState) {
this.pendingState = pendingState;
}
public byte[] getLastHash() {
return lastHash;
}
public void setLastHash(byte[] lastHash) {
this.lastHash = lastHash;
}
public byte[] getCurrentHash() {
return currentHash;
}
public void setCurrentHash(byte[] currentHash) {
this.currentHash = currentHash;
}
}