use of io.nuls.kernel.utils.VarInt in project nuls by nuls-io.
the class UtxoLedgerServiceImpl method verifyCoinData.
/**
* 此txList是待打包的块中的交易,所以toList是下一步的UTXO,应该校验它
* coinData的交易和txList同处一个块中,txList中的to可能是coinData的from,
* 也就是可能存在,在同一个块中,下一笔输入就是上一笔的输出,所以需要校验它
* bestHeight is used when switch chain.
*
* @return ValidateResult
*/
@Override
public ValidateResult verifyCoinData(Transaction transaction, Map<String, Coin> temporaryToMap, Set<String> temporaryFromSet, Long bestHeight) {
if (transaction == null || transaction.getCoinData() == null) {
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.NULL_PARAMETER);
}
try {
/*
校验开始
*/
CoinData coinData = transaction.getCoinData();
List<Coin> froms = coinData.getFrom();
int fromSize = froms.size();
TransactionSignature transactionSignature = new TransactionSignature();
// 交易签名反序列化
if (transaction.needVerifySignature() && fromSize > 0) {
try {
transactionSignature.parse(transaction.getTransactionSignature(), 0);
} catch (NulsException e) {
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.LEDGER_P2PKH_SCRIPT_ERROR);
}
}
// 保存Set用于验证自身双花
if (temporaryFromSet == null) {
temporaryFromSet = new HashSet<>();
}
Na fromTotal = Na.ZERO;
byte[] fromBytes;
// 保存在数据库中或者txList中的utxo数据
Coin fromOfFromCoin = null;
byte[] fromAddressBytes = null;
/**
* 存放真实地址(如果为脚本验证的情况fromAddressBytes存的是脚本信息)
*/
byte[] realAddressBytes = null;
for (int i = 0; i < froms.size(); i++) {
Coin from = froms.get(i);
fromBytes = from.getOwner();
// 验证是否可花费, 校验的coinData的fromUTXO,检查数据库中是否存在此UTXO
fromOfFromCoin = utxoLedgerUtxoStorageService.getUtxo(fromBytes);
// 检查txList中是否存在此UTXO
if (temporaryToMap != null && fromOfFromCoin == null) {
fromOfFromCoin = temporaryToMap.get(asString(fromBytes));
}
if (null == fromOfFromCoin) {
// 如果既不存在于txList的to中(如果txList不为空),又不存在于数据库中,那么这是一笔问题数据,进一步检查是否存在这笔交易,交易有就是双花,没有就是孤儿交易,则返回失败
if (null != utxoLedgerTransactionStorageService.getTxBytes(LedgerUtil.getTxHashBytes(fromBytes))) {
return ValidateResult.getFailedResult(CLASS_NAME, TransactionErrorCode.TRANSACTION_REPEATED);
} else {
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.ORPHAN_TX);
}
} else {
fromAddressBytes = fromOfFromCoin.getOwner();
realAddressBytes = fromOfFromCoin.getAddress();
// pierre add 非合约转账(从合约转出)交易,验证fromAdress是否是合约地址,如果是,则返回失败,非合约转账(从合约转出)交易不能转出合约地址资产
if (transaction.getType() != ContractConstant.TX_TYPE_CONTRACT_TRANSFER) {
boolean isContractAddress = contractService.isContractAddress(realAddressBytes);
if (isContractAddress) {
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.DATA_ERROR);
}
}
// 验证地址中的公钥hash160和交易中的公钥hash160是否相等,不相等则说明这笔utxo不属于交易发出者
boolean signtureValidFlag = false;
if (transaction.needVerifySignature()) {
if (transactionSignature != null) {
if (fromAddressBytes != null && transactionSignature.getScripts() != null && transactionSignature.getScripts().size() > 0) {
if (fromAddressBytes.length != Address.ADDRESS_LENGTH) {
Script scriptPubkey = new Script(fromAddressBytes);
for (Script scriptSig : transactionSignature.getScripts()) {
signtureValidFlag = scriptSig.correctlyNulsSpends(transaction, 0, scriptPubkey);
if (signtureValidFlag) {
break;
}
}
} else {
for (Script scriptSig : transactionSignature.getScripts()) {
Script redeemScript = new Script(scriptSig.getChunks().get(scriptSig.getChunks().size() - 1).data);
Address address = new Address(NulsContext.getInstance().getDefaultChainId(), NulsContext.P2SH_ADDRESS_TYPE, SerializeUtils.sha256hash160(redeemScript.getProgram()));
Script publicScript = SignatureUtil.createOutputScript(address.getAddressBytes());
signtureValidFlag = scriptSig.correctlyNulsSpends(transaction, 0, publicScript);
if (signtureValidFlag) {
break;
}
}
}
} else {
if (transactionSignature.getP2PHKSignatures() != null && transactionSignature.getP2PHKSignatures().size() != 0) {
for (P2PHKSignature signature : transactionSignature.getP2PHKSignatures()) {
signtureValidFlag = AddressTool.checkPublicKeyHash(realAddressBytes, signature.getSignerHash160());
if (signtureValidFlag) {
break;
}
}
}
}
}
if (!signtureValidFlag) {
Log.warn("public key hash160 check error.");
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.INVALID_INPUT);
}
}
if (java.util.Arrays.equals(realAddressBytes, NulsConstant.BLACK_HOLE_ADDRESS) || java.util.Arrays.equals(realAddressBytes, NulsConstant.BLACK_HOLE_ADDRESS_TEST_NET)) {
return ValidateResult.getFailedResult(CLASS_NAME, KernelErrorCode.ADDRESS_IS_BLOCK_HOLE);
}
if (NulsContext.getInstance().getDefaultChainId() != SerializeUtils.bytes2Short(realAddressBytes)) {
return ValidateResult.getFailedResult(CLASS_NAME, KernelErrorCode.ADDRESS_IS_NOT_BELONGS_TO_CHAIN);
}
}
// 验证非解锁类型的交易及解锁类型的交易
if (!transaction.isUnlockTx()) {
// 验证非解锁类型的交易,验证是否可用,检查是否还在锁定时间内
if (bestHeight == null) {
if (!fromOfFromCoin.usable()) {
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.UTXO_UNUSABLE);
}
} else {
if (!fromOfFromCoin.usable(bestHeight)) {
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.UTXO_UNUSABLE);
}
}
} else {
// 验证解锁类型的交易
if (fromOfFromCoin.getLockTime() != -1) {
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.UTXO_STATUS_CHANGE);
}
}
// 验证与待确认交易列表中是否有双花,既是待校验交易的fromUtxo是否和txList中的fromUtxo重复,有重复则是双花
if (temporaryFromSet != null && !temporaryFromSet.add(asString(fromBytes))) {
if (i > 0) {
for (int x = 0; x < i; x++) {
Coin theFrom = froms.get(i);
temporaryFromSet.remove(asString(theFrom.getOwner()));
}
}
return ValidateResult.getFailedResult(CLASS_NAME, TransactionErrorCode.TRANSACTION_REPEATED);
}
// 验证from的锁定时间和金额
if (!(fromOfFromCoin.getNa().equals(from.getNa()) && fromOfFromCoin.getLockTime() == from.getLockTime())) {
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.DATA_ERROR);
}
fromTotal = fromTotal.add(fromOfFromCoin.getNa());
from.setFrom(fromOfFromCoin);
}
List<Coin> tos = coinData.getTo();
Na toTotal = Na.ZERO;
byte[] txBytes = transaction.getHash().serialize();
for (int i = 0; i < tos.size(); i++) {
Coin to = tos.get(i);
// 如果不是调用合约的类型,并且合约地址作为nuls接收者,则返回错误,非合约交易不能转入nuls(CoinBase交易不过此验证)
if (ContractConstant.TX_TYPE_CALL_CONTRACT != transaction.getType() && AddressTool.validContractAddress(to.getOwner())) {
Log.error("Ledger verify error: {}.", ContractErrorCode.NON_CONTRACTUAL_TRANSACTION_NO_TRANSFER.getEnMsg());
return ValidateResult.getFailedResult(CLASS_NAME, ContractErrorCode.NON_CONTRACTUAL_TRANSACTION_NO_TRANSFER);
}
toTotal = toTotal.add(to.getNa());
if (temporaryToMap != null) {
temporaryToMap.put(asString(ArraysTool.concatenate(txBytes, new VarInt(i).encode())), to);
}
}
// 验证输出不能大于输入
if (fromTotal.compareTo(toTotal) < 0) {
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.INVALID_AMOUNT);
}
} catch (Exception e) {
Log.error(e);
return ValidateResult.getFailedResult(CLASS_NAME, KernelErrorCode.SYS_UNKOWN_EXCEPTION);
}
return ValidateResult.getSuccessResult();
}
use of io.nuls.kernel.utils.VarInt in project nuls by nuls-io.
the class UtxoLedgerServiceImpl method saveCoinData.
private Result saveCoinData(Transaction tx) throws IOException {
CoinData coinData = tx.getCoinData();
// TestLog-
if (coinData != null) {
BatchOperation batch = utxoLedgerUtxoStorageService.createWriteBatch();
// 删除utxo已花费 - from
List<Coin> froms = coinData.getFrom();
for (Coin from : froms) {
// TestLog+
// Coin preFrom = utxoLedgerUtxoStorageService.getUtxo(from.());
// if (preFrom != null) {
// Log.info("花费:height: +" + tx.getBlockHeight() + ", “+txHash-" + tx.getHash() + ", " + Hex.encode(from.()));
// }
// Log.info("delete utxo:" + Hex.encode(from.()));
// TestLog-
batch.delete(from.getOwner());
}
// 保存utxo - to
byte[] txHashBytes = tx.getHash().serialize();
List<Coin> tos = coinData.getTo();
for (int i = 0, length = tos.size(); i < length; i++) {
try {
byte[] owner = Arrays.concatenate(txHashBytes, new VarInt(i).encode());
// Log.info("129 save utxo:::" + Hex.encode(owner));
batch.put(owner, tos.get(i).serialize());
} catch (IOException e) {
Log.error(e);
return Result.getFailed(KernelErrorCode.IO_ERROR);
}
}
// 执行批量
Result batchResult = batch.executeBatch();
if (batchResult.isFailed()) {
return batchResult;
}
}
return Result.getSuccess();
}
use of io.nuls.kernel.utils.VarInt in project nuls by nuls-io.
the class UtxoLedgerServiceImpl method unlockTxCoinData.
@Override
public Result unlockTxCoinData(Transaction tx, long newockTime) throws NulsException {
if (tx == null || tx.getCoinData() == null) {
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.NULL_PARAMETER);
}
try {
CoinData coinData = tx.getCoinData();
List<Coin> tos = coinData.getTo();
boolean isExistLockUtxo = false;
Coin needUnLockUtxo = null;
int needUnLockUtxoIndex = 0;
for (Coin to : tos) {
if (to.getLockTime() == -1) {
isExistLockUtxo = true;
needUnLockUtxo = to;
break;
}
needUnLockUtxoIndex++;
}
if (!isExistLockUtxo) {
return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.UTXO_STATUS_CHANGE);
}
byte[] txHashBytes = txHashBytes = tx.getHash().serialize();
Coin needUnLockUtxoNew = new Coin(needUnLockUtxo.getOwner(), needUnLockUtxo.getNa(), newockTime);
needUnLockUtxoNew.setFrom(needUnLockUtxo.getFrom());
Result result = utxoLedgerUtxoStorageService.saveUtxo(Arrays.concatenate(txHashBytes, new VarInt(needUnLockUtxoIndex).encode()), needUnLockUtxoNew);
if (result.isFailed()) {
Result rollbackResult = rollbackUnlockTxCoinData(tx);
if (rollbackResult.isFailed()) {
throw new NulsException(rollbackResult.getErrorCode());
}
}
return result;
} catch (IOException e) {
Result rollbackResult = rollbackUnlockTxCoinData(tx);
if (rollbackResult.isFailed()) {
throw new NulsException(rollbackResult.getErrorCode());
}
Log.error(e);
return Result.getFailed(KernelErrorCode.IO_ERROR);
}
}
use of io.nuls.kernel.utils.VarInt in project nuls by nuls-io.
the class TransactionResource method getTxByHash.
@GET
@Path("/hash/{hash}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "根据hash查询交易")
@ApiResponses(value = { @ApiResponse(code = 200, message = "success", response = TransactionDto.class) })
public RpcClientResult getTxByHash(@ApiParam(name = "hash", value = "交易hash", required = true) @PathParam("hash") String hash) {
if (StringUtils.isBlank(hash)) {
return Result.getFailed(LedgerErrorCode.NULL_PARAMETER).toRpcClientResult();
}
if (!NulsDigestData.validHash(hash)) {
return Result.getFailed(LedgerErrorCode.PARAMETER_ERROR).toRpcClientResult();
}
Result result = null;
try {
Transaction tx = ledgerService.getTx(NulsDigestData.fromDigestHex(hash));
if (tx == null) {
result = Result.getFailed(TransactionErrorCode.TX_NOT_EXIST);
} else {
tx.setStatus(TxStatusEnum.CONFIRMED);
TransactionDto txDto = null;
CoinData coinData = tx.getCoinData();
String fromAddress = null;
if (tx.getTransactionSignature() != null) {
TransactionSignature signature = new TransactionSignature();
signature.parse(new NulsByteBuffer(tx.getTransactionSignature()));
if (signature.getP2PHKSignatures() != null && signature.getP2PHKSignatures().size() == 1) {
byte[] addressBytes = AddressTool.getAddress(signature.getP2PHKSignatures().get(0).getPublicKey());
fromAddress = AddressTool.getStringAddressByBytes(addressBytes);
}
}
if (coinData != null) {
// 组装from数据
List<Coin> froms = coinData.getFrom();
if (froms != null && froms.size() > 0) {
byte[] fromHash, owner;
int fromIndex;
NulsDigestData fromHashObj;
Transaction fromTx;
Coin fromUtxo;
for (Coin from : froms) {
if (fromAddress != null) {
from.setFromAddress(fromAddress);
} else {
owner = from.getOwner();
// owner拆分出txHash和index
fromHash = LedgerUtil.getTxHashBytes(owner);
fromIndex = LedgerUtil.getIndex(owner);
// 查询from UTXO
fromHashObj = new NulsDigestData();
fromHashObj.parse(fromHash, 0);
fromTx = ledgerService.getTx(fromHashObj);
fromUtxo = fromTx.getCoinData().getTo().get(fromIndex);
from.setFrom(fromUtxo);
}
}
}
txDto = new TransactionDto(tx);
List<OutputDto> outputDtoList = new ArrayList<>();
// 组装to数据
List<Coin> tos = coinData.getTo();
if (tos != null && tos.size() > 0) {
byte[] txHashBytes = tx.getHash().serialize();
String txHash = hash;
OutputDto outputDto = null;
Coin to, temp;
long bestHeight = NulsContext.getInstance().getBestHeight();
long currentTime = TimeService.currentTimeMillis();
long lockTime;
for (int i = 0, length = tos.size(); i < length; i++) {
to = tos.get(i);
outputDto = new OutputDto(to);
outputDto.setTxHash(txHash);
outputDto.setIndex(i);
temp = utxoLedgerUtxoStorageService.getUtxo(Arrays.concatenate(txHashBytes, new VarInt(i).encode()));
if (temp == null) {
// 已花费
outputDto.setStatus(3);
} else {
lockTime = temp.getLockTime();
if (lockTime < 0) {
// 共识锁定
outputDto.setStatus(2);
} else if (lockTime == 0) {
// 正常未花费
outputDto.setStatus(0);
} else if (lockTime > NulsConstant.BlOCKHEIGHT_TIME_DIVIDE) {
// 判定是否时间高度锁定
if (lockTime > currentTime) {
// 时间高度锁定
outputDto.setStatus(1);
} else {
// 正常未花费
outputDto.setStatus(0);
}
} else {
// 判定是否区块高度锁定
if (lockTime > bestHeight) {
// 区块高度锁定
outputDto.setStatus(1);
} else {
// 正常未花费
outputDto.setStatus(0);
}
}
}
outputDtoList.add(outputDto);
}
}
txDto.setOutputs(outputDtoList);
// 计算交易实际发生的金额
calTransactionValue(txDto);
}
result = Result.getSuccess();
result.setData(txDto);
}
} catch (NulsRuntimeException e) {
Log.error(e);
result = Result.getFailed(e.getErrorCode());
} catch (Exception e) {
Log.error(e);
result = Result.getFailed(LedgerErrorCode.SYS_UNKOWN_EXCEPTION);
}
return result.toRpcClientResult();
}
use of io.nuls.kernel.utils.VarInt in project nuls by nuls-io.
the class LocalUtxoServiceImpl method unlockCoinData.
@Override
public Result<List<byte[]>> unlockCoinData(Transaction tx, long newLockTime) {
List<byte[]> addresses = new ArrayList<>();
CoinData coinData = tx.getCoinData();
if (coinData != null) {
List<Coin> tos = coinData.getTo();
Coin to;
for (int i = 0, length = tos.size(); i < length; i++) {
to = tos.get(i);
if (to.getLockTime() == -1L) {
Coin needUnLockUtxoNew = new Coin(to.getOwner(), to.getNa(), newLockTime);
needUnLockUtxoNew.setFrom(to.getFrom());
try {
byte[] outKey = ArraysTool.concatenate(tx.getHash().serialize(), new VarInt(i).encode());
saveUTXO(outKey, needUnLockUtxoNew.serialize());
addresses.add(to.getAddress());
} catch (IOException e) {
throw new NulsRuntimeException(e);
}
// todo , think about weather to add a transaction history
break;
}
}
}
return Result.getSuccess().setData(addresses);
}
Aggregations