Skip to content

Commit

Permalink
Merge pull request tronprotocol#682 from tronprotocol/develop
Browse files Browse the repository at this point in the history
merge develop
  • Loading branch information
zhaohong authored May 9, 2018
2 parents 8a4dd22 + 62536c6 commit aed6daf
Show file tree
Hide file tree
Showing 72 changed files with 2,284 additions and 767 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ Then observe whether block synchronization success,If synchronization successf
# Quick Start
Read the [Quick Start](http://wiki.tron.network/en/latest/quick_start.html).
Read the [Quick Start](http://wiki.tron.network/en/latest/Quick_Start.html).
# Community
Expand Down
25 changes: 25 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -226,4 +226,29 @@ task stest(type:Test){
exceptionFormat = 'full'
showStackTraces = "true"
}
}

def binaryRelease(taskName,jarName,mainClass) {
return tasks.create("${taskName}", Jar) {
baseName = jarName
version = null
from(sourceSets.main.output) {
include "/**"
}

from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}

manifest {
attributes "Main-Class": "${mainClass}"
}
}
}

artifacts {
archives(binaryRelease('buildSolidityNodeJar','SolidityNode','org.tron.program.SolidityNode'),
binaryRelease('buildFullNodeJar','FullNode','org.tron.program.FullNode'))
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
Expand Down Expand Up @@ -205,7 +206,7 @@ private void trimTable() {
if (nodeHandlerMap.size() > NODES_TRIM_THRESHOLD) {
List<NodeHandler> sorted = new ArrayList<>(nodeHandlerMap.values());
// reverse sort by reputation
sorted.sort((o1, o2) -> o1.getNodeStatistics().getReputation() - o2.getNodeStatistics().getReputation());
sorted.sort(Comparator.comparingInt(o -> o.getNodeStatistics().getReputation()));
for (NodeHandler handler : sorted) {
nodeHandlerMap.remove(getKey(handler.getNode()));
if (nodeHandlerMap.size() <= MAX_NODES) {
Expand Down Expand Up @@ -287,8 +288,7 @@ public List<NodeHandler> getNodes(Predicate<NodeHandler> predicate, int limit) {
filtered.size());

//TODO: here can use head num sort.
filtered.sort((o1, o2) -> o2.getNodeStatistics().getReputation() - o1.getNodeStatistics()
.getReputation());
filtered.sort(Comparator.comparingInt((NodeHandler o) -> o.getNodeStatistics().getReputation()).reversed());

return CollectionUtils.truncate(filtered, limit);
}
Expand Down Expand Up @@ -322,8 +322,7 @@ public synchronized void addDiscoverListener(DiscoverListener listener,

public synchronized String dumpAllStatistics() {
List<NodeHandler> l = new ArrayList<>(nodeHandlerMap.values());
l.sort((o1, o2) -> -(o1.getNodeStatistics().getReputation() - o2.getNodeStatistics()
.getReputation()));
l.sort(Comparator.comparingInt((NodeHandler o) -> o.getNodeStatistics().getReputation()).reversed());

StringBuilder sb = new StringBuilder();
int zeroReputCount = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public UDPListener(final NodeManager nodeManager) {
}

public void start() throws Exception {
NioEventLoopGroup group = new NioEventLoopGroup(1);
NioEventLoopGroup group = new NioEventLoopGroup(args.getUdpNettyWorkThreadNum());
try {
discoveryExecutor = new DiscoveryExecutor(nodeManager);
discoveryExecutor.start();
Expand Down
8 changes: 6 additions & 2 deletions src/main/java/org/tron/common/overlay/server/Channel.java
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,18 @@ public void disconnect(ReasonCode reason) {
}

public void processException(Throwable throwable){
Throwable baseThrowable = throwable;
while (baseThrowable.getCause() != null){
baseThrowable = baseThrowable.getCause();
}
String errMsg = throwable.getMessage();
SocketAddress address = ctx.channel().remoteAddress();
if (throwable instanceof ReadTimeoutException){
logger.error("Read timeout, {}", address);
}else if(baseThrowable instanceof P2pException){
logger.error("type: {}, info: {}, {}", ((P2pException) throwable).getType(), errMsg, address);
}else if (errMsg != null && errMsg.contains("Connection reset by peer")){
logger.error("{}, {}", errMsg, address);
}else if(throwable instanceof P2pException){
logger.error("type: {}, info: {}, {}", ((P2pException) throwable).getType(), errMsg, address);
}else {
logger.error("exception caught, {}", address, throwable);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public PeerServer(final Args args, final ApplicationContext ctx) {
public void start(int port) {

bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup(args.getTcpNettyWorkThreadNum());
tronChannelInitializer = ctx.getBean(TronChannelInitializer.class, "");

tronChannelInitializer.setNodeImpl(p2pNode);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/tron/common/overlay/server/SyncPool.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public class SyncPool {

public static final Logger logger = LoggerFactory.getLogger("SyncPool");

private static final long WORKER_TIMEOUT = 15;
private static final long WORKER_TIMEOUT = 16;

private final List<PeerConnection> activePeers = Collections.synchronizedList(new ArrayList<PeerConnection>());

Expand Down
8 changes: 8 additions & 0 deletions src/main/java/org/tron/common/utils/Sha256Hash.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ public class Sha256Hash implements Serializable, Comparable<Sha256Hash> {

private final byte[] bytes;

private long blockNum;


private byte[] generateBlockId(long blockNum, Sha256Hash blockHash) {
byte[] numBytes = Longs.toByteArray(blockNum);
Expand All @@ -60,16 +62,22 @@ private byte[] generateBlockId(long blockNum, byte[] blockHash) {
return hash;
}

public long getBlockNum(){
return blockNum;
}

public Sha256Hash(long num, byte[] hash) {
byte[] rawHashBytes = this.generateBlockId(num, hash);
checkArgument(rawHashBytes.length == LENGTH);
this.bytes = rawHashBytes;
this.blockNum = num;
}

public Sha256Hash(long num, Sha256Hash hash) {
byte[] rawHashBytes = this.generateBlockId(num, hash);
checkArgument(rawHashBytes.length == LENGTH);
this.bytes = rawHashBytes;
this.blockNum = num;
}

/**
Expand Down
79 changes: 34 additions & 45 deletions src/main/java/org/tron/core/Wallet.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,19 @@
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tron.api.GrpcAPI;
import org.tron.api.GrpcAPI.AccountList;
import org.tron.api.GrpcAPI.AssetIssueList;
import org.tron.api.GrpcAPI.BlockList;
import org.tron.api.GrpcAPI.NumberMessage;
import org.tron.api.GrpcAPI.Return.response_code;
import org.tron.api.GrpcAPI.WitnessList;
import org.tron.common.crypto.ECKey;
import org.tron.common.crypto.Hash;
import org.tron.common.overlay.message.Message;
import org.tron.common.utils.Base58;
import org.tron.common.utils.ByteArray;
import org.tron.common.utils.ByteUtil;
import org.tron.common.utils.Utils;
import org.tron.core.capsule.AccountCapsule;
import org.tron.core.capsule.AssetIssueCapsule;
Expand All @@ -53,14 +56,8 @@
import org.tron.core.exception.ValidateSignatureException;
import org.tron.core.net.message.TransactionMessage;
import org.tron.core.net.node.NodeImpl;
import org.tron.protos.Contract.AccountCreateContract;
import org.tron.protos.Contract.AssetIssueContract;
import org.tron.protos.Contract.ParticipateAssetIssueContract;
import org.tron.protos.Contract.TransferAssetContract;
import org.tron.protos.Contract.TransferContract;
import org.tron.protos.Contract.VoteWitnessContract;
import org.tron.protos.Contract.WitnessCreateContract;
import org.tron.protos.Contract.WitnessUpdateContract;
import org.tron.protos.Protocol.Account;
import org.tron.protos.Protocol.Block;
import org.tron.protos.Protocol.Transaction;
Expand Down Expand Up @@ -115,7 +112,7 @@ public static void setAddressPreFixByte(byte addressPreFixByte) {
}

public static boolean addressValid(byte[] address) {
if (address == null || address.length == 0) {
if (ByteUtil.isNullOrZeroArray(address)) {
logger.warn("Warning: Address is empty !!");
return false;
}
Expand Down Expand Up @@ -207,60 +204,61 @@ public Transaction createTransaction(TransferContract contract) {
/**
* Broadcast a transaction.
*/
public boolean broadcastTransaction(Transaction signaturedTransaction) {
public GrpcAPI.Return broadcastTransaction(Transaction signaturedTransaction) {
GrpcAPI.Return.Builder builder = GrpcAPI.Return.newBuilder();
TransactionCapsule trx = new TransactionCapsule(signaturedTransaction);
try {
Message message = new TransactionMessage(signaturedTransaction);
if (message.getData().length > Constant.TRANSACTION_MAX_BYTE_SIZE) {
throw new TooBigTransactionException("too big transaction, the size is " + message.getData().length + " bytes");
throw new TooBigTransactionException(
"too big transaction, the size is " + message.getData().length + " bytes");
}
dbManager.pushTransactions(trx);
p2pNode.broadcast(message);
return true;
return builder.setResult(true).setCode(response_code.SUCCESS).build();
} catch (ValidateSignatureException e) {
logger.error(e.getMessage(), e);
return builder.setResult(false).setCode(response_code.SIGERROR)
.setMessage(ByteString.copyFromUtf8("validate signature error"))
.build();
} catch (ContractValidateException e) {
logger.error(e.getMessage(), e);
return builder.setResult(false).setCode(response_code.CONTRACT_VALIDATE_ERROR)
.setMessage(ByteString.copyFromUtf8("contract validate error"))
.build();
} catch (ContractExeException e) {
logger.error(e.getMessage(), e);
return builder.setResult(false).setCode(response_code.CONTRACT_EXE_ERROR)
.setMessage(ByteString.copyFromUtf8("contract execute error"))
.build();
} catch (ValidateBandwidthException e) {
logger.error("high freq", e);
return builder.setResult(false).setCode(response_code.BANDWITH_ERROR)
.setMessage(ByteString.copyFromUtf8("high freq error"))
.build();
} catch (DupTransactionException e) {
logger.error("dup trans", e);
return builder.setResult(false).setCode(response_code.DUP_TRANSACTION_ERROR)
.setMessage(ByteString.copyFromUtf8("dup transaction"))
.build();
} catch (TaposException e) {
logger.debug("tapos error", e);
return builder.setResult(false).setCode(response_code.TAPOS_ERROR)
.setMessage(ByteString.copyFromUtf8("Tapos check error"))
.build();
} catch (TooBigTransactionException e) {
logger.debug("transaction error", e);
} catch (Exception e){
return builder.setResult(false).setCode(response_code.TOO_BIG_TRANSACTION_ERROR)
.setMessage(ByteString.copyFromUtf8("TooBigTransactionException"))
.build();
} catch (Exception e) {
logger.error("exception caught", e);
return builder.setResult(false).setCode(response_code.OTHER_ERROR)
.setMessage(ByteString.copyFromUtf8("other error"))
.build();
}
return false;
}

@Deprecated
public Transaction createAccount(AccountCreateContract contract) {
AccountStore accountStore = dbManager.getAccountStore();
return new TransactionCapsule(contract, accountStore).getInstance();
}

@Deprecated
public Transaction createTransaction(VoteWitnessContract voteWitnessContract) {
return new TransactionCapsule(voteWitnessContract).getInstance();
}

@Deprecated
public Transaction createTransaction(AssetIssueContract assetIssueContract) {
return new TransactionCapsule(assetIssueContract).getInstance();
}
@Deprecated
public Transaction createTransaction(WitnessCreateContract witnessCreateContract) {
return new TransactionCapsule(witnessCreateContract).getInstance();
}

@Deprecated
public Transaction createTransaction(WitnessUpdateContract witnessUpdateContract) {
return new TransactionCapsule(witnessUpdateContract).getInstance();
}

public Block getNowBlock() {
try {
Expand Down Expand Up @@ -295,15 +293,6 @@ public WitnessList getWitnessList() {
.forEach(witnessCapsule -> builder.addWitnesses(witnessCapsule.getInstance()));
return builder.build();
}
@Deprecated
public Transaction createTransaction(TransferAssetContract transferAssetContract) {
return new TransactionCapsule(transferAssetContract).getInstance();
}
@Deprecated
public Transaction createTransaction(
ParticipateAssetIssueContract participateAssetIssueContract) {
return new TransactionCapsule(participateAssetIssueContract).getInstance();
}

public AssetIssueList getAssetIssueList() {
AssetIssueList.Builder builder = AssetIssueList.newBuilder();
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/tron/core/actuator/ActuatorFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ public static List<Actuator> createActuator(TransactionCapsule transactionCapsul

private static Actuator getActuatorByContract(Contract contract, Manager manager) {
switch (contract.getType()) {
case AccountCreateContract:
return new CreateAccountActuator(contract.getParameter(), manager);
case AccountUpdateContract:
return new UpdateAccountActuator(contract.getParameter(), manager);
case TransferContract:
return new TransferActuator(contract.getParameter(), manager);
case TransferAssetContract:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
@Slf4j
public class CreateAccountActuator extends AbstractActuator {


@Deprecated //Can not create account by api. Need send more than 1 trx , will create account if not exit.
CreateAccountActuator(Any contract, Manager dbManager) {
super(contract, dbManager);
}
Expand All @@ -31,7 +31,7 @@ public boolean execute(TransactionResultCapsule ret)

AccountCreateContract accountCreateContract = contract.unpack(AccountCreateContract.class);
AccountCapsule accountCapsule = new AccountCapsule(accountCreateContract,
System.currentTimeMillis());
dbManager.getHeadBlockTimeStamp());
dbManager.getAccountStore()
.put(accountCreateContract.getOwnerAddress().toByteArray(), accountCapsule);
ret.setStatus(fee, code.SUCESS);
Expand Down
44 changes: 31 additions & 13 deletions src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,38 @@ public boolean execute(TransactionResultCapsule ret) throws ContractExeException
AccountCapsule accountCapsule = dbManager.getAccountStore()
.get(freezeBalanceContract.getOwnerAddress().toByteArray());

long now = System.currentTimeMillis();
long now = dbManager.getHeadBlockTimeStamp();
long duration = freezeBalanceContract.getFrozenDuration() * 24 * 3600 * 1000L;

long newBandwidth = accountCapsule.getBandwidth()
+ calculateBandwidth(freezeBalanceContract);
long newBalance = accountCapsule.getBalance() - freezeBalanceContract.getFrozenBalance();

long nowFrozenBalance = accountCapsule.getFrozenBalance();
long newFrozenBalance = freezeBalanceContract.getFrozenBalance() + nowFrozenBalance;

Frozen newFrozen = Frozen.newBuilder()
.setFrozenBalance(freezeBalanceContract.getFrozenBalance())
.setFrozenBalance(newFrozenBalance)
.setExpireTime(now + duration)
.build();

long newBalance = accountCapsule.getBalance() - freezeBalanceContract.getFrozenBalance();
long newBandwidth = accountCapsule.getBandwidth() + calculateBandwidth(freezeBalanceContract);
accountCapsule.setInstance(accountCapsule.getInstance().toBuilder()
.addFrozen(newFrozen)
.setBalance(newBalance)
.setBandwidth(newBandwidth)
.build());
long frozenCount = accountCapsule.getFrozenCount();
assert (frozenCount >= 0);
if (frozenCount == 0) {
accountCapsule.setInstance(accountCapsule.getInstance().toBuilder()
.addFrozen(newFrozen)
.setBalance(newBalance)
.setBandwidth(newBandwidth)
.build());
}else {
assert frozenCount == 1;
accountCapsule.setInstance(accountCapsule.getInstance().toBuilder()
.setFrozen(0, newFrozen)
.setBalance(newBalance)
.setBandwidth(newBandwidth)
.build()
);
}

dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule);

Expand Down Expand Up @@ -101,10 +119,10 @@ public boolean validate() throws ContractValidateException {
throw new ContractValidateException("frozenBalance must be less than accountBalance");
}

long maxFrozenNumber = dbManager.getDynamicPropertiesStore().getMaxFrozenNumber();
if (accountCapsule.getFrozenCount() >= maxFrozenNumber) {
throw new ContractValidateException("max frozen number is: " + maxFrozenNumber);
}
// long maxFrozenNumber = dbManager.getDynamicPropertiesStore().getMaxFrozenNumber();
// if (accountCapsule.getFrozenCount() >= maxFrozenNumber) {
// throw new ContractValidateException("max frozen number is: " + maxFrozenNumber);
// }

long frozenDuration = freezeBalanceContract.getFrozenDuration();
long minFrozenTime = dbManager.getDynamicPropertiesStore().getMinFrozenTime();
Expand Down
Loading

0 comments on commit aed6daf

Please sign in to comment.