Skip to content

Commit

Permalink
Merge pull request #53 from XDagger/tuweni-bytes-refactor
Browse files Browse the repository at this point in the history
use tuweni bytes refactor
  • Loading branch information
LucasMLK authored Jun 20, 2021
2 parents 31f3b6e + fab7b09 commit d824c94
Show file tree
Hide file tree
Showing 79 changed files with 1,012 additions and 886 deletions.
7 changes: 4 additions & 3 deletions src/main/java/io/xdag/Kernel.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.tuweni.bytes.Bytes32;

import java.net.InetAddress;
import java.net.UnknownHostException;
Expand Down Expand Up @@ -212,13 +213,13 @@ public synchronized void testStart() throws Exception {
firstAccount = new Block(config, XdagTime.getCurrentTimestamp(), null, null, false, null,null, -1);
firstAccount.signOut(wallet.getDefKey());
poolMiner = new Miner(firstAccount.getHash());
xdagStats.setOurLastBlockHash(firstAccount.getHashLow());
xdagStats.setOurLastBlockHash(firstAccount.getHashLow().toArray());
if(xdagStats.getGlobalMiner() == null) {
xdagStats.setGlobalMiner(firstAccount.getHash());
xdagStats.setGlobalMiner(firstAccount.getHash().toArray());
}
blockchain.tryToConnect(firstAccount);
} else {
poolMiner = new Miner(xdagStats.getGlobalMiner());
poolMiner = new Miner(Bytes32.wrap(xdagStats.getGlobalMiner()));
}
log.info("Blockchain init");

Expand Down
3 changes: 2 additions & 1 deletion src/main/java/io/xdag/Launcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,11 @@ protected CommandLine parseOptions(String[] args) throws ParseException {
}

protected Config buildConfig(String[] args) throws Exception {
Config config = new MainnetConfig();
Config config = null;
for (String arg : args) {
switch (arg) {
case "-t" -> config = new TestnetConfig();
default -> config = new MainnetConfig();
}
}
config.changePara(args);
Expand Down
39 changes: 23 additions & 16 deletions src/main/java/io/xdag/cli/Commands.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.bytes.MutableBytes32;
import org.bouncycastle.util.encoders.Hex;

import java.math.BigInteger;
Expand Down Expand Up @@ -123,15 +125,17 @@ public String balance(String address) {
if (StringUtils.isEmpty(address)) {
return "Balance:"+String.format("%.9f", amount2xdag(kernel.getBlockchain().getXdagStats().getBalance())) + " XDAG";
} else {
byte[] hash;
// byte[] key = new byte[32];
Bytes32 hash;
MutableBytes32 key = MutableBytes32.create();
if (StringUtils.length(address) == 32) {
hash = address2Hash(address);
} else {
hash = BasicUtils.getHash(address);
}
byte[] key = new byte[32];
System.arraycopy(Objects.requireNonNull(hash), 8, key, 8, 24);
Block block = kernel.getBlockStore().getBlockInfoByHash(key);
// System.arraycopy(Objects.requireNonNull(hash), 8, key, 8, 24);
key.set(8, Objects.requireNonNull(hash).slice(8,24));
Block block = kernel.getBlockStore().getBlockInfoByHash(Bytes32.wrap(key));
return "Balance:"+String.format("%.9f", amount2xdag(block.getInfo().getAmount())) + " XDAG";
}
}
Expand All @@ -143,15 +147,16 @@ public String balance(String address) {
* @param address receiver address
* @return Transaction hash
*/
public String xfer(double sendAmount, byte[] address, String remark) {
public String xfer(double sendAmount, Bytes32 address, String remark) {

StringBuilder str = new StringBuilder();
str.append("Transaction :{ ").append("\n");


long amount = xdag2amount(sendAmount);
byte[] to = new byte[32];
System.arraycopy(address, 8, to, 8, 24);
MutableBytes32 to = MutableBytes32.create();
// System.arraycopy(address, 8, to, 8, 24);
to.set(8,address.slice(8,24));

// 待转账余额
AtomicLong remain = new AtomicLong(amount);
Expand Down Expand Up @@ -197,7 +202,7 @@ public String xfer(double sendAmount, byte[] address, String remark) {



private List<BlockWrapper> createTransactionBlock(Map<Address, ECKeyPair> ourKeys, byte[] to, String remark) {
private List<BlockWrapper> createTransactionBlock(Map<Address, ECKeyPair> ourKeys, Bytes32 to, String remark) {
// 判断是否有remark
int hasRemark = remark==null ? 0:1;

Expand Down Expand Up @@ -251,7 +256,7 @@ private List<BlockWrapper> createTransactionBlock(Map<Address, ECKeyPair> ourKey
}


private BlockWrapper createTransaction(byte[] to, long amount, Map<Address, ECKeyPair> keys, String remark) {
private BlockWrapper createTransaction(Bytes32 to, long amount, Map<Address, ECKeyPair> keys, String remark) {

List<Address> tos = Lists.newArrayList(new Address(to, XDAG_FIELD_OUT, amount));

Expand Down Expand Up @@ -337,10 +342,12 @@ public void connectbylibp2p(String server,int port,String ip){
* @param blockhash blockhash
* @return block info
*/
public String block(byte[] blockhash) {
public String block(Bytes32 blockhash) {
try {
byte[] hashLow = new byte[32];
System.arraycopy(blockhash, 8, hashLow, 8, 24);
// byte[] hashLow = new byte[32];
MutableBytes32 hashLow = MutableBytes32.create();
// System.arraycopy(blockhash, 8, hashLow, 8, 24);
hashLow.set(8, blockhash.slice(8, 24));
Block block = kernel.getBlockStore().getRawBlockByHash(hashLow);
return printBlockInfo(block);
} catch (Exception e) {
Expand All @@ -350,7 +357,7 @@ public String block(byte[] blockhash) {
}

public String block(String address) {
byte[] hashlow = address2Hash(address);
Bytes32 hashlow = address2Hash(address);
if (hashlow != null) {
return block(hashlow);
} else {
Expand Down Expand Up @@ -389,7 +396,7 @@ public String printBlockInfo(Block block) {
inputs = new StringBuilder();
for (int i = 0; i < block.getInputs().size(); i++) {
inputs.append(String.format(" input: %s %.9f\n",
hash2Address(kernel.getBlockchain().getBlockByHash(block.getInputs().get(i).getHashLow(), false).getInfo().getHash()), amount2xdag(block.getInputs().get(i).getAmount().longValue())
hash2Address(Bytes32.wrap(kernel.getBlockchain().getBlockByHash(block.getInputs().get(i).getHashLow(), false).getInfo().getHash())), amount2xdag(block.getInputs().get(i).getAmount().longValue())
));
}
}
Expand All @@ -398,7 +405,7 @@ public String printBlockInfo(Block block) {
outputs = new StringBuilder();
for (int i = 0; i < block.getOutputs().size(); i++) {
outputs.append(String.format(" output: %s %.9f\n",
hash2Address(kernel.getBlockchain().getBlockByHash(block.getOutputs().get(i).getHashLow(), false).getInfo().getHash()), amount2xdag(block.getOutputs().get(i).getAmount().longValue())
hash2Address(Bytes32.wrap(kernel.getBlockchain().getBlockByHash(block.getOutputs().get(i).getHashLow(), false).getInfo().getHash())), amount2xdag(block.getOutputs().get(i).getAmount().longValue())
));
}
}
Expand All @@ -413,7 +420,7 @@ public String printBlockInfo(Block block) {
block.getInfo().getDifficulty().toString(16),
hash2Address(block.getHash()), amount2xdag(block.getInfo().getAmount()),
//fee目前为0
block.getInfo().getRef()==null?"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA":hash2Address(block.getInfo().getRef()),0.0
block.getInfo().getRef()==null?"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA":hash2Address(Bytes32.wrap(block.getInfo().getRef())),0.0
)
+"\n"
+(inputs==null?"":inputs.toString())+(outputs==null?"":outputs.toString())
Expand Down
13 changes: 7 additions & 6 deletions src/main/java/io/xdag/cli/Shell.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.tuweni.bytes.Bytes32;
import org.jline.builtins.Options;
import org.jline.builtins.TTop;
import org.jline.builtins.telnet.Telnet;
Expand Down Expand Up @@ -154,7 +155,7 @@ private void processBlock(CommandInput input) {

String address = argv.get(0);
try {
byte[] hash;
Bytes32 hash;
if (address.length() == 32) {
// as address
hash = address2Hash(address);
Expand All @@ -166,7 +167,7 @@ private void processBlock(CommandInput input) {
println("No param");
return;
}
println(commands.block(hash));
println(commands.block(Bytes32.wrap(hash)));
} catch (Exception e) {
println("Argument is incorrect.");
}
Expand Down Expand Up @@ -288,7 +289,7 @@ private void processXfer(CommandInput input) {
return;
}

byte[] hash;
Bytes32 hash;
double amount = BasicUtils.getDouble(argv.get(0));

String remark = argv.size()==3 ? argv.get(2):null;
Expand All @@ -299,16 +300,16 @@ private void processXfer(CommandInput input) {
}

if (argv.get(1).length() == 32) {
hash = address2Hash(argv.get(1));
hash = Bytes32.wrap(address2Hash(argv.get(1)));
} else {
hash = BasicUtils.getHash(argv.get(1));
hash = Bytes32.wrap(BasicUtils.getHash(argv.get(1)));
}
if (hash == null) {
println("No Address");
return;
}

if (kernel.getBlockchain().getBlockByHash(hash, false) == null) {
if (kernel.getBlockchain().getBlockByHash(Bytes32.wrap(hash), false) == null) {
// if (kernel.getAccountStore().getAccountBlockByHash(hash, false) == null) {
println("Incorrect address");
return;
Expand Down
37 changes: 17 additions & 20 deletions src/main/java/io/xdag/consensus/SyncManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,11 @@
import io.xdag.net.Channel;
import io.xdag.net.libp2p.discovery.DiscoveryPeer;
import io.xdag.net.manager.XdagChannelManager;
import io.xdag.utils.ByteArrayWrapper;
import io.xdag.utils.BytesUtils;
import io.xdag.utils.XdagTime;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Hex;
import org.apache.tuweni.bytes.Bytes32;

import javax.annotation.Nonnull;
import java.math.BigInteger;
Expand All @@ -49,7 +47,6 @@
import java.util.concurrent.atomic.AtomicLong;

import static io.xdag.core.ImportResult.*;
import static io.xdag.utils.BytesUtils.equalBytes;

@Slf4j
@Getter
Expand Down Expand Up @@ -93,7 +90,7 @@ public SyncManager(Kernel kernel) {
private Queue<BlockWrapper> blockQueue = new ConcurrentLinkedQueue<>();

/** Queue for the link block don't exist */
private ConcurrentHashMap<ByteArrayWrapper, Queue<BlockWrapper>> syncMap = new ConcurrentHashMap<>();
private ConcurrentHashMap<Bytes32, Queue<BlockWrapper>> syncMap = new ConcurrentHashMap<>();

public void start() {
log.debug("Download receiveBlock run...");
Expand Down Expand Up @@ -145,11 +142,11 @@ public boolean isTimeToStart() {
/** Processing the queue adding blocks to the chain. */
//todo:修改共识
public ImportResult importBlock(BlockWrapper blockWrapper) {
log.debug("importBlock:{}", BytesUtils.toHexString(blockWrapper.getBlock().getHash()));
ImportResult importResult = blockchain.tryToConnect(new Block(new XdagBlock(blockWrapper.getBlock().getXdagBlock().getData())));
log.debug("importBlock:{}", blockWrapper.getBlock().getHash().toHexString());
ImportResult importResult = blockchain.tryToConnect(new Block(new XdagBlock(blockWrapper.getBlock().getXdagBlock().getData().toArray())));

if (importResult == EXIST) {
log.debug("Block have exist:" + Hex.toHexString(blockWrapper.getBlock().getHash()));
log.debug("Block have exist:" + blockWrapper.getBlock().getHash().toHexString());
}

Config config = kernel.getConfig();
Expand Down Expand Up @@ -192,7 +189,7 @@ public boolean isSyncDone() {
public synchronized ImportResult validateAndAddNewBlock(BlockWrapper blockWrapper) {
blockWrapper.getBlock().parse();
ImportResult result = importBlock(blockWrapper);
log.debug("validateAndAddNewBlock:{}, {}", Hex.toHexString(blockWrapper.getBlock().getHashLow()), result);
log.debug("validateAndAddNewBlock:{}, {}", blockWrapper.getBlock().getHashLow().toHexString(), result);
switch (result) {
case EXIST:
case IMPORTED_BEST:
Expand All @@ -201,8 +198,8 @@ public synchronized ImportResult validateAndAddNewBlock(BlockWrapper blockWrappe
break;
case NO_PARENT: {
if (syncPushBlock(blockWrapper, result.getHashlow())) {
log.debug("push block:{}, NO_PARENT {}", Hex.toHexString(blockWrapper.getBlock().getHashLow()),
Hex.toHexString(result.getHashlow()));
log.debug("push block:{}, NO_PARENT {}", blockWrapper.getBlock().getHashLow().toHexString(),
result.getHashlow().toHexString());
List<Channel> channels = channelMgr.getActiveChannels();
for (Channel channel : channels) {
if(channel.getNode().equals(blockWrapper.getRemoteNode())) {
Expand Down Expand Up @@ -232,19 +229,19 @@ public synchronized ImportResult validateAndAddNewBlock(BlockWrapper blockWrappe
* @param hashLow
* 缺失的parent哈希
*/
public boolean syncPushBlock(BlockWrapper blockWrapper, byte[] hashLow) {
public boolean syncPushBlock(BlockWrapper blockWrapper, Bytes32 hashLow) {
AtomicBoolean r = new AtomicBoolean(true);
long now = System.currentTimeMillis();
ByteArrayWrapper refKey = new ByteArrayWrapper(hashLow);
// ByteArrayWrapper refKey = new ByteArrayWrapper(hashLow);
Queue<BlockWrapper> newQueue = Queues.newConcurrentLinkedQueue();
blockWrapper.setTime(now);
newQueue.add(blockWrapper);
blockchain.getXdagStats().nwaitsync++;
syncMap.merge(refKey, newQueue,
syncMap.merge(hashLow, newQueue,
(oldQ, newQ) -> {
blockchain.getXdagStats().nwaitsync--;
for(BlockWrapper b : oldQ) {
if (equalBytes(b.getBlock().getHashLow(), blockWrapper.getBlock().getHashLow())) {
if (b.getBlock().getHashLow().equals(blockWrapper.getBlock().getHashLow())) {
// after 64 sec must resend block request
if(now - b.getTime() > 64 * 1000) {
b.setTime(now);
Expand All @@ -270,10 +267,10 @@ public boolean syncPushBlock(BlockWrapper blockWrapper, byte[] hashLow) {
*/
public void syncPopBlock(BlockWrapper blockWrapper) {
Block block = blockWrapper.getBlock();
ByteArrayWrapper key = new ByteArrayWrapper(block.getHashLow());
Queue<BlockWrapper> queue = syncMap.getOrDefault(key,null);
// ByteArrayWrapper key = new ByteArrayWrapper(block.getHashLow().toArray());
Queue<BlockWrapper> queue = syncMap.getOrDefault(block.getHashLow(),null);
if (queue!=null) {
syncMap.remove(key);
syncMap.remove(block.getHashLow());
blockchain.getXdagStats().nwaitsync--;
queue.forEach(bw -> {
ImportResult importResult = importBlock(bw);
Expand All @@ -287,8 +284,8 @@ public void syncPopBlock(BlockWrapper blockWrapper) {
break;
case NO_PARENT:
if (syncPushBlock(bw, importResult.getHashlow())) {
log.debug("push block:{}, NO_PARENT {}", Hex.toHexString(bw.getBlock().getHashLow()),
Hex.toHexString(importResult.getHashlow()));
log.debug("push block:{}, NO_PARENT {}", bw.getBlock().getHashLow().toHexString(),
importResult.getHashlow().toHexString());
List<Channel> channels = channelMgr.getActiveChannels();
for (Channel channel : channels) {
if (channel.getNode().equals(bw.getRemoteNode())) {
Expand Down
Loading

0 comments on commit d824c94

Please sign in to comment.