forked from tronprotocol/java-tron
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeerBuilder.java
More file actions
80 lines (66 loc) · 2.31 KB
/
PeerBuilder.java
File metadata and controls
80 lines (66 loc) · 2.31 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
package org.tron.peer;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.name.Names;
import org.tron.consensus.client.BlockchainClientListener;
import org.tron.consensus.client.Client;
import org.tron.core.Blockchain;
import org.tron.core.UTXOSet;
import org.tron.crypto.ECKey;
import org.tron.storage.leveldb.LevelDbDataSourceImpl;
import org.tron.utils.ByteArray;
import org.tron.wallet.Wallet;
import javax.inject.Inject;
/**
* Builds a peer
* <p>
* Set the key and type before calling build
*/
public class PeerBuilder {
private Blockchain blockchain;
private UTXOSet utxoSet;
private Wallet wallet;
private ECKey key;
private String type;
private Injector injector;
@Inject
public PeerBuilder(Injector injector) {
this.injector = injector;
}
private void buildBlockchain() {
if (wallet == null) throw new IllegalStateException("Wallet must be set before building the blockchain");
if (type == null) throw new IllegalStateException("Type must be set before building the blockchain");
blockchain = new Blockchain(
injector.getInstance(Key.get(LevelDbDataSourceImpl.class, Names.named("block"))),
ByteArray.toHexString(wallet.getAddress()),
this.type
);
}
private void buildUTXOSet() {
if (blockchain == null) throw new IllegalStateException("Blockchain must be set before building the UTXOSet");
utxoSet = injector.getInstance(UTXOSet.class);
utxoSet.setBlockchain(blockchain);
utxoSet.reindex();
}
private void buildWallet() {
if (key == null) throw new IllegalStateException("Key must be set before building the wallet");
wallet = new Wallet(key);
}
public PeerBuilder setType(String type) {
this.type = type;
return this;
}
public PeerBuilder setKey(ECKey key) {
this.key = key;
return this;
}
public Peer build() {
buildWallet();
buildBlockchain();
buildUTXOSet();
Peer peer = new Peer(type, blockchain, utxoSet, wallet, key);
peer.setClient(injector.getInstance(Client.class));
blockchain.addListener(new BlockchainClientListener(injector.getInstance(Client.class), peer));
return peer;
}
}