Skip to content

Commit

Permalink
use tuweni crypto refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
LucasMLK committed Jul 1, 2021
1 parent 1ae6012 commit 51e04b8
Show file tree
Hide file tree
Showing 59 changed files with 848 additions and 1,388 deletions.
17 changes: 12 additions & 5 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -280,11 +280,6 @@
</build>

<dependencies>
<dependency>
<groupId>fr.acinq.bitcoin</groupId>
<artifactId>secp256k1-jni</artifactId>
<version>1.3</version>
</dependency>

<dependency>
<groupId>org.jetbrains</groupId>
Expand Down Expand Up @@ -549,6 +544,18 @@
</exclusions>
</dependency>

<dependency>
<groupId>org.apache.tuweni</groupId>
<artifactId>crypto</artifactId>
<version>1.3.0</version>
</dependency>

<dependency>
<groupId>org.apache.tuweni</groupId>
<artifactId>io</artifactId>
<version>1.3.0</version>
</dependency>

<dependency>
<groupId>org.apache.tuweni</groupId>
<artifactId>units</artifactId>
Expand Down
26 changes: 13 additions & 13 deletions src/main/java/io/xdag/cli/Commands.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import com.google.common.collect.Maps;
import io.xdag.Kernel;
import io.xdag.core.*;
import io.xdag.crypto.ECKeyPair;
import io.xdag.mine.MinerChannel;
import io.xdag.mine.miner.Miner;
import io.xdag.mine.miner.MinerCalculate;
Expand All @@ -42,6 +41,7 @@
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.bytes.MutableBytes32;
import org.apache.tuweni.crypto.SECP256K1;
import org.bouncycastle.util.encoders.Hex;

import java.math.BigInteger;
Expand Down Expand Up @@ -161,7 +161,7 @@ public String xfer(double sendAmount, Bytes32 address, String remark) {
// 待转账余额
AtomicLong remain = new AtomicLong(amount);
// 转账输入
Map<Address, ECKeyPair> ourBlocks = Maps.newHashMap();
Map<Address, SECP256K1.KeyPair> ourBlocks = Maps.newHashMap();

// our block select
kernel.getBlockStore().fetchOurBlocks(pair -> {
Expand Down Expand Up @@ -202,20 +202,20 @@ public String xfer(double sendAmount, Bytes32 address, String remark) {



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

List<BlockWrapper> res = new ArrayList<>();

// 遍历ourKeys 计算每个区块最多能放多少个
// int res = 1 + pairs.size() + to.size() + 3*keys.size() + (defKeyIndex == -1 ? 2 : 0);
LinkedList<Map.Entry<Address, ECKeyPair>> stack = new LinkedList<>(ourKeys.entrySet());
LinkedList<Map.Entry<Address, SECP256K1.KeyPair>> stack = new LinkedList<>(ourKeys.entrySet());

// 每次创建区块用到的keys
Map<Address, ECKeyPair> keys = new HashMap<>();
Map<Address, SECP256K1.KeyPair> keys = new HashMap<>();
// 保证key的唯一性
Set<ECKeyPair> keysPerBlock = new HashSet<>();
Set<SECP256K1.KeyPair> keysPerBlock = new HashSet<>();
// 放入defkey
keysPerBlock.add(kernel.getWallet().getDefKey());

Expand All @@ -224,7 +224,7 @@ private List<BlockWrapper> createTransactionBlock(Map<Address, ECKeyPair> ourKey
long amount = 0;

while (stack.size() > 0){
Map.Entry<Address,ECKeyPair> key = stack.peek();
Map.Entry<Address, SECP256K1.KeyPair> key = stack.peek();
base += 1;
int originSize = keysPerBlock.size();
keysPerBlock.add(key.getValue());
Expand Down Expand Up @@ -256,7 +256,7 @@ private List<BlockWrapper> createTransactionBlock(Map<Address, ECKeyPair> ourKey
}


private BlockWrapper createTransaction(Bytes32 to, long amount, Map<Address, ECKeyPair> keys, String remark) {
private BlockWrapper createTransaction(Bytes32 to, long amount, Map<Address, SECP256K1.KeyPair> keys, String remark) {

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

Expand All @@ -266,16 +266,16 @@ private BlockWrapper createTransaction(Bytes32 to, long amount, Map<Address, ECK
return null;
}

ECKeyPair defaultKey = kernel.getWallet().getDefKey();
SECP256K1.KeyPair defaultKey = kernel.getWallet().getDefKey();

boolean isdefaultKey = false;
// 签名
for (ECKeyPair ecKey : Set.copyOf(new HashMap<>(keys).values())) {
if (ecKey.equals(defaultKey)) {
for (SECP256K1.KeyPair key : Set.copyOf(new HashMap<>(keys).values())) {
if (key.equals(defaultKey)) {
isdefaultKey = true;
block.signOut(ecKey);
block.signOut(key);
} else {
block.signIn(ecKey);
block.signIn(key);
}
}
// 如果默认密钥被更改,需要重新对输出签名签属
Expand Down
51 changes: 26 additions & 25 deletions src/main/java/io/xdag/cli/XdagCli.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
import io.xdag.config.Config;
import io.xdag.config.Constants;
import io.xdag.config.TestnetConfig;
import io.xdag.crypto.ECKeyPair;
import io.xdag.crypto.Keys;
import io.xdag.crypto.MnemonicUtils;
import io.xdag.crypto.SecureRandomUtils;
Expand All @@ -40,6 +39,8 @@
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.ParseException;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.crypto.SECP256K1;

import java.io.*;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -192,11 +193,11 @@ protected void start() throws IOException {
}

// create a new account if the wallet is empty
List<ECKeyPair> accounts = wallet.getAccounts();
List<SECP256K1.KeyPair> accounts = wallet.getAccounts();
if (accounts.isEmpty()) {
ECKeyPair key = wallet.addAccountWithNextHdKey();
SECP256K1.KeyPair key = wallet.addAccountWithNextHdKey();
wallet.flush();
System.out.println("New Address:" + BytesUtils.toHexString(Keys.toBytesAddress(key)));
System.out.println("New Address:" + Keys.getAddress(key));
}

// start kernel
Expand Down Expand Up @@ -242,22 +243,22 @@ protected void createAccount() {
System.out.println("Please init HD Wallet account first!");
return;
}
ECKeyPair key = wallet.addAccountWithNextHdKey();
SECP256K1.KeyPair key = wallet.addAccountWithNextHdKey();
if (wallet.flush()) {
System.out.println("New Address:" + BytesUtils.toHexString(Keys.toBytesAddress(key)));
System.out.println("PublicKey:" + BytesUtils.toHexString(key.getPublicKey().toByteArray()));
System.out.println("New Address:" + Keys.getAddress(key));
System.out.println("PublicKey:" + key.publicKey().toHexString());
}
}

protected void listAccounts() {
Wallet wallet = loadAndUnlockWallet();
List<ECKeyPair> accounts = wallet.getAccounts();
List<SECP256K1.KeyPair> accounts = wallet.getAccounts();

if (accounts.isEmpty()) {
System.out.println("Account Missing");
} else {
for (int i = 0; i < accounts.size(); i++) {
System.out.println("Address:" + i + " " + BytesUtils.toHexString(Keys.toBytesAddress(accounts.get(i))));
System.out.println("Address:" + i + " " + Keys.getAddress(accounts.get(i)));
}
}
}
Expand Down Expand Up @@ -285,20 +286,19 @@ protected void exit(int code) {

protected void dumpPrivateKey(String address) {
Wallet wallet = loadAndUnlockWallet();
byte[] addressBytes = BytesUtils.hexStringToBytes(address);
ECKeyPair account = wallet.getAccount(addressBytes);
SECP256K1.KeyPair account = wallet.getAccount(address);
if (account == null) {
System.out.println("Address Not In Wallet");
} else {
System.out.println("Private:" + BytesUtils.toHexString(account.getPrivateKey().toByteArray()));
System.out.println("Private:" + account.secretKey().bytes().toHexString());
}
System.out.println("Private Dump Successfully!");
}

protected boolean importPrivateKey(String key) {
Wallet wallet = loadAndUnlockWallet();
byte[] keyBytes = BytesUtils.hexStringToBytes(key);
ECKeyPair account = ECKeyPair.create(keyBytes);
SECP256K1.SecretKey secretKey = SECP256K1.SecretKey.fromBytes(Bytes32.fromHexString(key));
SECP256K1.KeyPair account = SECP256K1.KeyPair.fromSecretKey(secretKey);

boolean accountAdded = wallet.addAccount(account);
if (!accountAdded) {
Expand All @@ -312,8 +312,8 @@ protected boolean importPrivateKey(String key) {
return false;
}

System.out.println("Address:" + BytesUtils.toHexString(Keys.toBytesAddress(account)));
System.out.println("PublicKey:" + BytesUtils.toHexString(account.getPublicKey().toByteArray()));
System.out.println("Address:" + Keys.getAddress(account));
System.out.println("PublicKey:" + account.publicKey().toHexString());
System.out.println("Private Key Imported Successfully!");
return true;
}
Expand Down Expand Up @@ -351,27 +351,28 @@ protected boolean convertOldWallet(File file) {
}
String password = readPassword("Old wallet password:");
String random = readPassword("Old wallet random:");
List<ECKeyPair> keyList = readOldWallet(password, random, file);
for(ECKeyPair key : keyList) {
System.out.println("PrivateKey:" + BytesUtils.toHexString(key.getPrivateKey().toByteArray()));
System.out.println(" PublicKey:" + BytesUtils.toHexString(key.getPublicKey().toByteArray()));
System.out.println(" Address:" + BytesUtils.toHexString(Keys.toBytesAddress(key)));
List<SECP256K1.KeyPair> keyList = readOldWallet(password, random, file);
for(SECP256K1.KeyPair key : keyList) {
System.out.println("PrivateKey:" + key.secretKey().bytes().toHexString());
System.out.println(" PublicKey:" + key.publicKey().toHexString());
System.out.println(" Address:" + Keys.getAddress(key));
}
System.out.println("Old Wallet Converted Successfully!");
return true;
}

public List<ECKeyPair> readOldWallet(String password, String random, File walletDatFile) {
public List<SECP256K1.KeyPair> readOldWallet(String password, String random, File walletDatFile) {
byte[] priv32Encrypted = new byte[32];
int keysNum = 0;
List<ECKeyPair> keyList = new ArrayList<>();
List<SECP256K1.KeyPair> keyList = new ArrayList<>();
Native.general_dnet_key(password, random);
try (FileInputStream fileInputStream = new FileInputStream(walletDatFile)) {
while (fileInputStream.read(priv32Encrypted) != -1) {
byte[] priv32 = Native.uncrypt_wallet_key(priv32Encrypted, keysNum++);
BytesUtils.arrayReverse(priv32);
ECKeyPair ecKey = ECKeyPair.create(Numeric.toBigInt(priv32));
keyList.add(ecKey);
SECP256K1.SecretKey secretKey = SECP256K1.SecretKey.fromBytes(Bytes32.wrap(priv32));
SECP256K1.KeyPair key = SECP256K1.KeyPair.fromSecretKey(secretKey);
keyList.add(key);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/io/xdag/config/AbstractConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
@Setter
public class AbstractConfig implements Config, AdminSpec, PoolSpec, NodeSpec, WalletSpec, RPCSpec {
protected String configName;
protected byte id;

// =========================
// Admin spec
Expand Down Expand Up @@ -146,8 +147,9 @@ public void setDir() {
}


protected AbstractConfig(String rootDir, String configName) {
protected AbstractConfig(String rootDir, byte id, String configName) {
this.rootDir = rootDir;
this.id = id;
this.configName = configName;

getSetting();
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/io/xdag/config/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@
*/
public interface Config {

/**
* Id.
*/
byte getId();

/**
* Config File Name.
*/
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/io/xdag/config/DevnetConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
public class DevnetConfig extends AbstractConfig {

public DevnetConfig() {
super("devnet", "xdag-devnet.config");
super("devnet", (byte)1, "xdag-devnet.config");
this.whitelistUrl = StringUtils.EMPTY;

this.xdagEra = 0x16900000000L;
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/io/xdag/config/MainnetConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
public class MainnetConfig extends AbstractConfig {

public MainnetConfig() {
super("mainnet", "xdag-mainnet.config");
super("mainnet", (byte)3, "xdag-mainnet.config");
this.whitelistUrl = "https://raw.githubusercontent.com/XDagger/xdag/master/client/netdb-white.txt";


Expand Down
2 changes: 1 addition & 1 deletion src/main/java/io/xdag/config/TestnetConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
public class TestnetConfig extends AbstractConfig {

public TestnetConfig() {
super("testnet","xdag-testnet.config");
super("testnet", (byte)2, "xdag-testnet.config");
this.whitelistUrl = "https://raw.githubusercontent.com/XDagger/xdag/master/client/netdb-white-testnet.txt";

// testnet wait 1 epoch
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/io/xdag/consensus/XdagPow.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@

import io.xdag.Kernel;
import io.xdag.core.*;
import io.xdag.crypto.Hash;
import io.xdag.listener.Listener;
import io.xdag.mine.MinerChannel;
import io.xdag.mine.manager.AwardManager;
Expand All @@ -42,6 +41,7 @@
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.bytes.MutableBytes;
import org.apache.tuweni.crypto.Hash;

import java.io.IOException;
import java.util.ArrayList;
Expand Down Expand Up @@ -324,7 +324,7 @@ private Task createTaskByRandomXBlock(Block block, long sendTime) {
RandomXMemory memory = randomXUtils.getGlobalMemory()[(int) randomXUtils.getRandomXPoolMemIndex() & 1];

// Bytes32 rxHash = Hash.sha256(Bytes.wrap(BytesUtils.subArray(block.getXdagBlock().getData(),0,480)));
Bytes32 rxHash = Hash.sha256(block.getXdagBlock().getData().slice(0,480));
Bytes32 rxHash = Hash.sha2_256(block.getXdagBlock().getData().slice(0,480));

// todo
task[0] = new XdagField(rxHash.mutableCopy());
Expand Down
Loading

0 comments on commit 51e04b8

Please sign in to comment.