diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index f35538c0961..c7a5a6f4160 100644 --- a/.github/workflows/pr-build.yml +++ b/.github/workflows/pr-build.yml @@ -197,7 +197,7 @@ jobs: debian11-x86_64-gradle- - name: Build - run: ./gradlew clean build --no-daemon --no-build-cache + run: ./gradlew clean build --no-daemon - name: Toolkit jar smoke test run: | @@ -209,7 +209,7 @@ jobs: java -jar "$JAR" keystore --help - name: Test with RocksDB engine - run: ./gradlew :framework:testWithRocksDb --no-daemon --no-build-cache + run: ./gradlew :framework:testWithRocksDb --no-daemon - name: Generate module coverage reports run: ./gradlew jacocoTestReport --no-daemon @@ -265,11 +265,11 @@ jobs: # this PR. The only output we need from this job is the jacoco XML for # coverage diffing, so we must not let a stale test failure block it. continue-on-error: true - run: ./gradlew clean build --no-daemon --no-build-cache + run: ./gradlew clean build --no-daemon - name: Test with RocksDB engine (base) continue-on-error: true - run: ./gradlew :framework:testWithRocksDb --no-daemon --no-build-cache + run: ./gradlew :framework:testWithRocksDb --no-daemon - name: Generate module coverage reports (base) run: ./gradlew jacocoTestReport --no-daemon diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml index 506a823a4f7..6a7337ce310 100644 --- a/.github/workflows/pr-check.yml +++ b/.github/workflows/pr-check.yml @@ -43,9 +43,16 @@ jobs: errors.push(`PR title is too long (${title.length}/72 characters).`); } - // 2. Conventional format check - const conventionalRegex = /^(feat|fix|refactor|docs|style|test|chore|ci|perf|build|revert)(\([^)]+\))?:\s\S.*/; - if (title && !conventionalRegex.test(title)) { + // 2. Conventional format check (require a space after the colon) + const titlePrefix = '(?:feat|fix|refactor|docs|style|test|chore|ci|perf|build|revert)(?:[(][^)]+[)])?'; + const missingSpaceAfterColonRegex = new RegExp(`^${titlePrefix}:[^ ]`); + const conventionalRegex = new RegExp(`^${titlePrefix}: [^ ].*`); + if (title && missingSpaceAfterColonRegex.test(title)) { + errors.push( + 'PR title must include a space after the colon.\n' + + ' Example: `feat(tvm): add blob opcodes`' + ); + } else if (title && !conventionalRegex.test(title)) { errors.push( 'PR title must follow conventional format: `type(scope): description`\n' + ' Allowed types: ' + allowedTypes.map(t => `\`${t}\``).join(', ') + '\n' + @@ -60,7 +67,7 @@ jobs: // 4. Description part should not start with a capital letter if (title) { - const descMatch = title.match(/^\w+(?:\([^)]+\))?:\s*(.+)/); + const descMatch = title.match(/^\w+(?:\([^)]+\))?: (.+)/); if (descMatch) { const desc = descMatch[1]; if (/^[A-Z]/.test(desc)) { diff --git a/.github/workflows/pr-reviewer.yml b/.github/workflows/pr-reviewer.yml index bf124acf576..e10b98aaf1c 100644 --- a/.github/workflows/pr-reviewer.yml +++ b/.github/workflows/pr-reviewer.yml @@ -59,13 +59,23 @@ jobs: const normalize = s => s.toLowerCase().replace(/[\s\-_]/g, ''); // ── Extract scope from conventional commit title ────────── - // Format: type(scope): description + // Formats documented by CONTRIBUTING.md: + // type(scope): description + // type: description // Also supports: type(scope1,scope2): description + // Only bare "ci" currently has an equivalent reviewer scope. const scopeMatch = title.match(/^\w+\(([^)]+)\):/); - const rawScope = scopeMatch ? scopeMatch[1] : null; + const bareTypeMatch = title.match(/^(\w+):/); + const inferredScope = !scopeMatch && bareTypeMatch?.[1].toLowerCase() === 'ci' + ? 'ci' + : null; + const rawScope = scopeMatch ? scopeMatch[1] : inferredScope; core.info(`PR title : ${title}`); core.info(`Raw scope: ${rawScope || '(none)'}`); + if (inferredScope) { + core.info('Inferred scope "ci" from bare "ci" PR title type.'); + } // ── Skip if reviewers already assigned ────────────────── const pr = await github.rest.pulls.get({ diff --git a/actuator/src/main/java/org/tron/core/actuator/VMActuator.java b/actuator/src/main/java/org/tron/core/actuator/VMActuator.java index d785951027b..aaf7647a274 100644 --- a/actuator/src/main/java/org/tron/core/actuator/VMActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/VMActuator.java @@ -25,6 +25,7 @@ import org.tron.common.runtime.InternalTransaction.TrxType; import org.tron.common.runtime.ProgramResult; import org.tron.common.runtime.vm.DataWord; +import org.tron.common.utils.ForkController; import org.tron.common.utils.StorageUtils; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; @@ -33,6 +34,7 @@ import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.ReceiptCapsule; +import org.tron.core.config.Parameter; import org.tron.core.db.EnergyProcessor; import org.tron.core.db.TransactionContext; import org.tron.core.exception.ContractExeException; @@ -189,7 +191,8 @@ public void execute(Object object) throws ContractExeException { throw e; } - VM.play(program, OperationRegistry.getTable()); + // Prepare the table once for this execution and all nested calls. + VM.play(program, OperationRegistry.prepareAndGetTable(isConstantCall)); result = program.getResult(); if (VMConfig.allowEnergyAdjustment()) { @@ -217,6 +220,9 @@ public void execute(Object object) throws ContractExeException { } else { result.spendEnergy(saveCodeEnergy); if (VMConfig.allowTvmConstantinople()) { + CreateSmartContract createContract = + ContractCapsule.getSmartContractFromTransaction(trx); + checkContractHashFields(createContract.getNewContract()); rootRepository.saveCode(program.getContractAddress().getNoLeadZeroesData(), code); } } @@ -293,6 +299,10 @@ public void execute(Object object) throws ContractExeException { result.setRuntimeError(result.getException().getMessage()); } logger.info("runtime result is :{}", result.getException().getMessage()); + } finally { + if (isConstantCall) { + VMConfig.clearLocalSnapshot(); + } } //use program returned fill context context.setProgramResult(result); @@ -303,10 +313,6 @@ public void execute(Object object) throws ContractExeException { .error(result.getException()) .toString(); - if (VMConfig.vmTraceCompressed()) { - traceContent = VMUtils.zipAndEncode(traceContent); - } - String txHash = Hex.toHexString(rootInternalTx.getHash()); VMUtils.saveProgramTraceFile(txHash, traceContent); } @@ -330,6 +336,7 @@ private void create() if (contract == null) { throw new ContractValidateException("Cannot get CreateSmartContract from transaction"); } + SmartContract newSmartContract; if (VMConfig.allowTvmCompatibleEvm()) { newSmartContract = contract.getNewContract().toBuilder().setVersion(1).build(); @@ -341,11 +348,7 @@ private void create() throw new ContractValidateException("OwnerAddress is not equals OriginAddress"); } - byte[] contractName = newSmartContract.getName().getBytes(); - - if (contractName.length > VMConstant.CONTRACT_NAME_LENGTH) { - throw new ContractValidateException("contractName's length cannot be greater than 32"); - } + checkContractNameLength(contract.getNewContract()); long percent = contract.getNewContract().getConsumeUserResourcePercent(); if (percent < 0 || percent > VMConstant.ONE_HUNDRED) { @@ -455,6 +458,22 @@ private void create() } + static void checkContractHashFields(SmartContract contract) { + if (!contract.getCodeHash().isEmpty() || !contract.getTrxHash().isEmpty()) { + MUtil.checkCPUTimeForContractHashFields(); + } + } + + static void checkContractNameLength(SmartContract contract) throws ContractValidateException { + int contractNameLength = + ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2) + ? contract.getNameBytes().size() + : contract.getName().getBytes().length; + if (contractNameLength > VMConstant.CONTRACT_NAME_LENGTH) { + throw new ContractValidateException("contractName's length cannot be greater than 32"); + } + } + /** * ** */ diff --git a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java index 74d332c5611..2c70a21ef3b 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -941,6 +941,21 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, } break; } + case ALLOW_OPTIMIZE_TVM_STORAGE: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_8_2_3)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_OPTIMIZE_TVM_STORAGE]"); + } + if (dynamicPropertiesStore.getAllowOptimizeTvmStorage() == 1) { + throw new ContractValidateException( + "[ALLOW_OPTIMIZE_TVM_STORAGE] has been valid, no need to propose again"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_OPTIMIZE_TVM_STORAGE] is only allowed to be 1"); + } + break; + } default: break; } @@ -1029,7 +1044,8 @@ public enum ProposalType { // current value, value range ALLOW_TVM_PRAGUE(95), // 0, 1 ALLOW_TVM_OSAKA(96), // 0, 1 ALLOW_HARDEN_RESOURCE_CALCULATION(97), // 0, 1 - ALLOW_HARDEN_EXCHANGE_CALCULATION(98); // 0, 1 + ALLOW_HARDEN_EXCHANGE_CALCULATION(98), // 0, 1 + ALLOW_OPTIMIZE_TVM_STORAGE(99); // 0, 1 private long code; ProposalType(long code) { diff --git a/actuator/src/main/java/org/tron/core/vm/Operation.java b/actuator/src/main/java/org/tron/core/vm/Operation.java index 87ff8fce749..80b25262089 100644 --- a/actuator/src/main/java/org/tron/core/vm/Operation.java +++ b/actuator/src/main/java/org/tron/core/vm/Operation.java @@ -52,4 +52,12 @@ public void execute(Program program) { public boolean isEnabled() { return enabled.getAsBoolean(); } + + public Operation adjustCost(Function newCost) { + return new Operation(opcode, require, ret, newCost, action, enabled); + } + + public Operation adjustAction(Consumer newAction) { + return new Operation(opcode, require, ret, cost, newAction, enabled); + } } diff --git a/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java b/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java index 8c078e843a2..28ce2147beb 100644 --- a/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java +++ b/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java @@ -7,12 +7,45 @@ public class OperationRegistry { + private static final Operation DEFAULT_MLOAD = new Operation( + Op.MLOAD, 1, 1, EnergyCost::getMloadCost, OperationActions::mLoadAction); + + private static final Operation DEFAULT_MSTORE = new Operation( + Op.MSTORE, 2, 0, EnergyCost::getMStoreCost, OperationActions::mStoreAction); + + private static final Operation DEFAULT_MSTORE8 = new Operation( + Op.MSTORE8, 2, 0, EnergyCost::getMStore8Cost, OperationActions::mStore8Action); + + private static final Operation ADJUSTED_MLOAD = + DEFAULT_MLOAD.adjustCost(EnergyCost::getMloadCost2); + + private static final Operation ADJUSTED_MSTORE = + DEFAULT_MSTORE.adjustCost(EnergyCost::getMStoreCost2); + + private static final Operation ADJUSTED_MSTORE8 = + DEFAULT_MSTORE8.adjustCost(EnergyCost::getMStore8Cost2); + + private static final Operation DEFAULT_VOTEWITNESS = new Operation( + Op.VOTEWITNESS, 4, 1, EnergyCost::getVoteWitnessCost, + OperationActions::voteWitnessAction, VMConfig::allowTvmVote); + + private static final Operation ADJUSTED_VOTEWITNESS = + DEFAULT_VOTEWITNESS.adjustCost(EnergyCost::getVoteWitnessCost2); + + private static final Operation OSAKA_VOTEWITNESS = + DEFAULT_VOTEWITNESS.adjustCost(EnergyCost::getVoteWitnessCost3); + + private static final Operation DEFAULT_SUICIDE = new Operation( + Op.SUICIDE, 1, 0, EnergyCost::getSuicideCost, OperationActions::suicideAction); + + private static final Operation ADJUSTED_SUICIDE = + DEFAULT_SUICIDE.adjustCost(EnergyCost::getSuicideCost2); + + private static final Operation RESTRICTED_SUICIDE = + DEFAULT_SUICIDE.adjustCost(EnergyCost::getSuicideCost3) + .adjustAction(OperationActions::suicideAction2); + public enum Version { - TRON_V1_0, - TRON_V1_1, - TRON_V1_2, - TRON_V1_3, - TRON_V1_4, TRON_V1_5, // add more // TRON_V2, @@ -21,13 +54,21 @@ public enum Version { private static final Map tableMap = new HashMap<>(); + // The newest version in use. Bump this when a newer operation set is added, + // together with newLatestOperationSet() below. + private static final Version LATEST_VERSION = Version.TRON_V1_5; + static { - tableMap.put(Version.TRON_V1_0, newTronV10OperationSet()); - tableMap.put(Version.TRON_V1_1, newTronV11OperationSet()); - tableMap.put(Version.TRON_V1_2, newTronV12OperationSet()); - tableMap.put(Version.TRON_V1_3, newTronV13OperationSet()); - tableMap.put(Version.TRON_V1_4, newTronV14OperationSet()); - tableMap.put(Version.TRON_V1_5, newTronV15OperationSet()); + tableMap.put(LATEST_VERSION, newLatestOperationSet()); + } + + // Constant calls get a dedicated instance of the newest table, isolated from + // the shared consensus table above. + private static final JumpTable CONSTANT_CALL_TABLE = newLatestOperationSet(); + + // The single place that decides which operation set is the newest. + private static JumpTable newLatestOperationSet() { + return newTronV15OperationSet(); } public static JumpTable newTronV10OperationSet() { @@ -74,28 +115,22 @@ public static JumpTable newTronV15OperationSet() { // Just for warming up class to avoid out_of_time public static void init() {} - public static JumpTable getTable() { - // always get the table which has the newest version - JumpTable table = tableMap.get(Version.TRON_V1_5); - - // next make the corresponding changes, exclude activating opcode - if (VMConfig.allowHigherLimitForMaxCpuTimeOfOneTx()) { - adjustMemOperations(table); - } - - if (VMConfig.allowEnergyAdjustment()) { - adjustForFairEnergy(table); - } - - if (VMConfig.allowTvmSelfdestructRestriction()) { - adjustSelfdestruct(table); - } + public static JumpTable prepareAndGetTable(boolean isConstantCall) { + JumpTable table = getTable(isConstantCall); + // Apply configuration-dependent changes once at the top level. + adjustTable(table); + return table; + } - if (VMConfig.allowTvmOsaka()) { - adjustVoteWitnessCost(table); - } + public static JumpTable getTable(boolean isConstantCall) { + return isConstantCall ? CONSTANT_CALL_TABLE : tableMap.get(LATEST_VERSION); + } - return table; + private static void adjustTable(JumpTable table) { + // Make the corresponding changes, excluding opcode activation. + adjustMemOperations(table); + adjustVoteWitness(table); + adjustSelfdestruct(table); } public static JumpTable newBaseOperationSet() { @@ -331,20 +366,11 @@ public static JumpTable newBaseOperationSet() { EnergyCost::getBaseTierCost, OperationActions::popAction)); - table.set(new Operation( - Op.MLOAD, 1, 1, - EnergyCost::getMloadCost, - OperationActions::mLoadAction)); + table.set(DEFAULT_MLOAD); - table.set(new Operation( - Op.MSTORE, 2, 0, - EnergyCost::getMStoreCost, - OperationActions::mStoreAction)); + table.set(DEFAULT_MSTORE); - table.set(new Operation( - Op.MSTORE8, 2, 0, - EnergyCost::getMStore8Cost, - OperationActions::mStore8Action)); + table.set(DEFAULT_MSTORE8); table.set(new Operation( Op.SLOAD, 1, 1, @@ -449,10 +475,7 @@ public static JumpTable newBaseOperationSet() { EnergyCost::getRevertCost, OperationActions::revertAction)); - table.set(new Operation( - Op.SUICIDE, 1, 0, - EnergyCost::getSuicideCost, - OperationActions::suicideAction)); + table.set(DEFAULT_SUICIDE); return table; } @@ -570,11 +593,7 @@ public static void appendFreezeOperations(JumpTable table) { public static void appendVoteOperations(JumpTable table) { BooleanSupplier proposal = VMConfig::allowTvmVote; - table.set(new Operation( - Op.VOTEWITNESS, 4, 1, - EnergyCost::getVoteWitnessCost, - OperationActions::voteWitnessAction, - proposal)); + table.set(DEFAULT_VOTEWITNESS); table.set(new Operation( Op.WITHDRAWREWARD, 0, 1, @@ -593,23 +612,6 @@ public static void appendLondonOperations(JumpTable table) { proposal)); } - public static void adjustMemOperations(JumpTable table) { - table.set(new Operation( - Op.MLOAD, 1, 1, - EnergyCost::getMloadCost2, - OperationActions::mLoadAction)); - - table.set(new Operation( - Op.MSTORE, 2, 0, - EnergyCost::getMStoreCost2, - OperationActions::mStoreAction)); - - table.set(new Operation( - Op.MSTORE8, 2, 0, - EnergyCost::getMStore8Cost2, - OperationActions::mStore8Action)); - } - public static void appendFreezeV2Operations(JumpTable table) { BooleanSupplier proposal = VMConfig::allowTvmFreezeV2; @@ -664,19 +666,6 @@ public static void appendShangHaiOperations(JumpTable table) { proposal)); } - public static void adjustForFairEnergy(JumpTable table) { - table.set(new Operation( - Op.VOTEWITNESS, 4, 1, - EnergyCost::getVoteWitnessCost2, - OperationActions::voteWitnessAction, - VMConfig::allowTvmVote)); - - table.set(new Operation( - Op.SUICIDE, 1, 0, - EnergyCost::getSuicideCost2, - OperationActions::suicideAction)); - } - public static void appendCancunOperations(JumpTable table) { BooleanSupplier proposal = VMConfig::allowTvmCancun; BooleanSupplier tvmBlobProposal = VMConfig::allowTvmBlob; @@ -722,18 +711,30 @@ public static void appendOsakaOperations(JumpTable table) { proposal)); } - public static void adjustSelfdestruct(JumpTable table) { - table.set(new Operation( - Op.SUICIDE, 1, 0, - EnergyCost::getSuicideCost3, - OperationActions::suicideAction2)); + public static void adjustMemOperations(JumpTable table) { + boolean adjusted = VMConfig.allowHigherLimitForMaxCpuTimeOfOneTx(); + table.set(adjusted ? ADJUSTED_MLOAD : DEFAULT_MLOAD); + table.set(adjusted ? ADJUSTED_MSTORE : DEFAULT_MSTORE); + table.set(adjusted ? ADJUSTED_MSTORE8 : DEFAULT_MSTORE8); } - public static void adjustVoteWitnessCost(JumpTable table) { - table.set(new Operation( - Op.VOTEWITNESS, 4, 1, - EnergyCost::getVoteWitnessCost3, - OperationActions::voteWitnessAction, - VMConfig::allowTvmVote)); + public static void adjustVoteWitness(JumpTable table) { + if (VMConfig.allowTvmOsaka()) { + table.set(OSAKA_VOTEWITNESS); + } else if (VMConfig.allowEnergyAdjustment()) { + table.set(ADJUSTED_VOTEWITNESS); + } else { + table.set(DEFAULT_VOTEWITNESS); + } + } + + public static void adjustSelfdestruct(JumpTable table) { + if (VMConfig.allowTvmSelfdestructRestriction()) { + table.set(RESTRICTED_SUICIDE); + } else if (VMConfig.allowEnergyAdjustment()) { + table.set(ADJUSTED_SUICIDE); + } else { + table.set(DEFAULT_SUICIDE); + } } } diff --git a/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java b/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java index 3993e8ed835..8f67ed3527d 100644 --- a/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java +++ b/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java @@ -982,9 +982,13 @@ public Pair execute(byte[] data) { } PairingCheck check = PairingCheck.create(); + long deadlineNs = pairingDeadlineNs(); // iterating over all pairs for (int offset = 0; offset < data.length; offset += PAIR_SIZE) { + if (deadlineNs < System.nanoTime()) { + throw Program.Exception.notEnoughTime("precompiled contract pair"); + } Pair pair = decodePair(data, offset); @@ -996,12 +1000,23 @@ public Pair execute(byte[] data) { check.addPair(pair.getLeft(), pair.getRight()); } - check.run(); + if (!check.run(deadlineNs)) { + throw Program.Exception.notEnoughTime("precompiled contract pair"); + } int result = check.result(); return Pair.of(true, new DataWord(result).getData()); } + /** Same skip as {@link Program#checkCPUTimeLimit}: debug and solidity nodes do not enforce it. */ + private long pairingDeadlineNs() { + if (CommonParameter.getInstance().isDebug() + || CommonParameter.getInstance().isSolidityNode()) { + return Long.MAX_VALUE; + } + return getVmShouldEndInUs() * VMConstant.ONE_THOUSAND; + } + private Pair decodePair(byte[] in, int offset) { byte[] x = parseWord(in, offset, 0); diff --git a/actuator/src/main/java/org/tron/core/vm/VMUtils.java b/actuator/src/main/java/org/tron/core/vm/VMUtils.java index 2f469e0579a..cbd6f61bf14 100644 --- a/actuator/src/main/java/org/tron/core/vm/VMUtils.java +++ b/actuator/src/main/java/org/tron/core/vm/VMUtils.java @@ -1,20 +1,14 @@ package org.tron.core.vm; import static java.lang.String.format; -import static org.apache.commons.codec.binary.Base64.encodeBase64String; import static org.tron.common.math.Maths.addExact; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; -import java.util.zip.Deflater; -import java.util.zip.DeflaterOutputStream; import lombok.extern.slf4j.Slf4j; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; @@ -29,8 +23,6 @@ @Slf4j(topic = "VM") public final class VMUtils { - private static final int BUF_SIZE = 4096; - private VMUtils() { } @@ -97,43 +89,6 @@ public static void saveProgramTraceFile(String txHash, String content) { } } - private static void write(InputStream in, OutputStream out, int bufSize) throws IOException { - try { - byte[] buf = new byte[bufSize]; - for (int count = in.read(buf); count != -1; count = in.read(buf)) { - out.write(buf, 0, count); - } - } finally { - closeQuietly(in); - closeQuietly(out); - } - } - - public static byte[] compress(byte[] bytes) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - ByteArrayInputStream in = new ByteArrayInputStream(bytes); - DeflaterOutputStream out = new DeflaterOutputStream(baos, new Deflater(), BUF_SIZE); - - write(in, out, BUF_SIZE); - - return baos.toByteArray(); - } - - public static byte[] compress(String content) throws IOException { - return compress(content.getBytes("UTF-8")); - } - - public static String zipAndEncode(String content) { - try { - return encodeBase64String(compress(content)); - } catch (Exception e) { - logger.error("Cannot zip or encode: ", e); - return content; - } - } - - public static boolean validateForSmartContract(Repository deposit, byte[] ownerAddress, byte[] toAddress, long amount) throws ContractValidateException { if (!DecodeUtil.addressValid(ownerAddress)) { diff --git a/actuator/src/main/java/org/tron/core/vm/config/ConfigLoader.java b/actuator/src/main/java/org/tron/core/vm/config/ConfigLoader.java index 35480935742..9d927f7039b 100644 --- a/actuator/src/main/java/org/tron/core/vm/config/ConfigLoader.java +++ b/actuator/src/main/java/org/tron/core/vm/config/ConfigLoader.java @@ -50,6 +50,7 @@ public static void load(StoreFactory storeFactory, boolean isolate) { snapshot.allowTvmSelfdestructRestriction = ds.getAllowTvmSelfdestructRestriction() == 1; snapshot.allowTvmOsaka = ds.getAllowTvmOsaka() == 1; snapshot.allowHardenResourceCalculation = ds.getAllowHardenResourceCalculation() == 1; + snapshot.allowOptimizeTvmStorage = ds.getAllowOptimizeTvmStorage() == 1; if (isolate) { VMConfig.setLocalSnapshot(snapshot); } else { diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/CancelAllUnfreezeV2Processor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/CancelAllUnfreezeV2Processor.java index ec1f4363205..6ee8b1245ce 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/CancelAllUnfreezeV2Processor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/CancelAllUnfreezeV2Processor.java @@ -19,6 +19,7 @@ import org.tron.core.vm.VMConstant; import org.tron.core.vm.nativecontract.param.CancelAllUnfreezeV2Param; import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.utils.MUtil; import org.tron.protos.Protocol; @Slf4j(topic = "VMProcessor") @@ -39,6 +40,10 @@ public void validate(CancelAllUnfreezeV2Param param, Repository repo) throws Con throw new ContractValidateException( ACCOUNT_EXCEPTION_STR + readableOwnerAddress + NOT_EXIST_STR); } + + if (accountCapsule.hasInvalidDelegatedV2()) { + MUtil.checkCPUTimeForInvalidDelegatedV2Balance(); + } } public Map execute(CancelAllUnfreezeV2Param param, Repository repo) throws ContractExeException { diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java index e7e932194ed..96c6e936b36 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java @@ -14,6 +14,7 @@ import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.vm.nativecontract.param.FreezeBalanceV2Param; import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.utils.MUtil; @Slf4j(topic = "VMProcessor") public class FreezeBalanceV2Processor { @@ -63,6 +64,10 @@ public void validate(FreezeBalanceV2Param param, Repository repo) throws Contrac "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); } } + + if (repo.isSelfDestructed(ownerAddress)) { + MUtil.checkCPUTimeForFreezeV2AfterSelfDestruct(); + } } public void execute(FreezeBalanceV2Param param, Repository repo) { diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java index af2cbf63a43..73ffb5f294b 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java @@ -23,6 +23,7 @@ import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.nativecontract.param.UnfreezeBalanceV2Param; import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.utils.MUtil; import org.tron.core.vm.utils.VoteRewardUtil; import org.tron.protos.Protocol; import org.tron.protos.contract.Common; @@ -86,6 +87,10 @@ public void validate(UnfreezeBalanceV2Param param, Repository repo) throw new ContractValidateException( "Invalid unfreeze_balance, [" + param.getUnfreezeBalance() + "] is invalid"); } + + if (accountCapsule.hasInvalidDelegatedV2()) { + MUtil.checkCPUTimeForInvalidDelegatedV2Balance(); + } } private boolean checkUnfreezeBalance( diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java index 0bcdb10d46f..982031aa672 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java @@ -17,6 +17,7 @@ import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.vm.nativecontract.param.WithdrawExpireUnfreezeParam; import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.utils.MUtil; import org.tron.protos.Protocol; @Slf4j(topic = "VMProcessor") @@ -52,6 +53,10 @@ public void validate(WithdrawExpireUnfreezeParam param, Repository repo) throws logger.debug(e.getMessage(), e); throw new ContractValidateException(e.getMessage()); } + + if (accountCapsule.hasInvalidDelegatedV2()) { + MUtil.checkCPUTimeForInvalidDelegatedV2Balance(); + } } private long getTotalWithdrawUnfreeze(List unfrozenV2List, long now) { diff --git a/actuator/src/main/java/org/tron/core/vm/program/ContractState.java b/actuator/src/main/java/org/tron/core/vm/program/ContractState.java index c6347b9a072..30ec0d24f34 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/ContractState.java +++ b/actuator/src/main/java/org/tron/core/vm/program/ContractState.java @@ -131,6 +131,16 @@ public boolean isNewContract(byte[] address) { return repository.isNewContract(address); } + @Override + public void markSelfDestruct(byte[] address) { + repository.markSelfDestruct(address); + } + + @Override + public boolean isSelfDestructed(byte[] address) { + return repository.isSelfDestructed(address); + } + @Override public void updateAccount(byte[] address, AccountCapsule accountCapsule) { repository.updateAccount(address, accountCapsule); diff --git a/actuator/src/main/java/org/tron/core/vm/program/Program.java b/actuator/src/main/java/org/tron/core/vm/program/Program.java index 590859a9fef..2be1eb80703 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/Program.java +++ b/actuator/src/main/java/org/tron/core/vm/program/Program.java @@ -512,12 +512,18 @@ public void suicide(DataWord obtainerAddress) { internalTx.setValue(internalTx.getValue() + expireUnfrozenBalance); } } + + getContractState().markSelfDestruct(owner); getResult().addDeleteAccount(this.getContractAddress()); } public void suicide2(DataWord obtainerAddress) { - byte[] owner = getContextAddress(); + + if (getContractState().isSelfDestructed(obtainerAddress.toTronAddress())) { + MUtil.checkCPUTimeForSelfDestructedBeneficiary(); + } + boolean isNewContract = getContractState().isNewContract(owner); if (isNewContract) { suicide(obtainerAddress); @@ -540,6 +546,7 @@ public void suicide2(DataWord obtainerAddress) { "suicide", nonce, getContractState().getAccount(owner).getAssetMapV2()); if (FastByteComparisons.isEqual(owner, obtainer)) { + getContractState().markSelfDestruct(owner); return; } @@ -579,6 +586,8 @@ public void suicide2(DataWord obtainerAddress) { internalTx.setValue(internalTx.getValue() + expireUnfrozenBalance); } } + + getContractState().markSelfDestruct(owner); } public Repository getContractState() { @@ -914,7 +923,8 @@ this, new DataWord(newAddress), getContractAddress(), value, DataWord.ZERO(), if (VMConfig.allowTvmCompatibleEvm()) { program.setContractVersion(getContractVersion()); } - VM.play(program, OperationRegistry.getTable()); + // Reuse the table prepared by the top-level execution. + VM.play(program, OperationRegistry.getTable(isConstantCall())); createResult = program.getResult(); getTrace().merge(program.getTrace()); // always commit nonce @@ -1146,7 +1156,8 @@ this, new DataWord(contextAddress), program.setContractVersion(invoke.getDeposit() .getContract(codeAddress).getContractVersion()); } - VM.play(program, OperationRegistry.getTable()); + // Reuse the table prepared by the top-level execution. + VM.play(program, OperationRegistry.getTable(isConstantCall())); callResult = program.getResult(); getTrace().merge(program.getTrace()); diff --git a/actuator/src/main/java/org/tron/core/vm/program/Storage.java b/actuator/src/main/java/org/tron/core/vm/program/Storage.java index 572af048081..1c2b15af863 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/Storage.java +++ b/actuator/src/main/java/org/tron/core/vm/program/Storage.java @@ -9,14 +9,27 @@ import org.tron.common.crypto.Hash; import org.tron.common.runtime.vm.DataWord; import org.tron.common.utils.ByteUtil; +import org.tron.common.utils.ForkController; import org.tron.core.capsule.StorageRowCapsule; +import org.tron.core.config.Parameter.ForkBlockVersionEnum; import org.tron.core.store.StorageRowStore; public class Storage { private static final int PREFIX_BYTES = 16; + private static final int WORD_BYTES = 32; + + private enum ReadKind { + NEW, OLD, EMPTY + } + @Getter private final Map rowCache = new HashMap<>(); + private final Map oldRowKeyOwners = new HashMap<>(); + private final Map readKinds = new HashMap<>(); + private final boolean optimizeTvmStorage; + private final boolean aliasCheckEnabled; + @Getter private byte[] addrHash; @Getter @@ -26,10 +39,12 @@ public class Storage { @Setter private int contractVersion; - public Storage(byte[] address, StorageRowStore store) { + public Storage(byte[] address, StorageRowStore store, boolean optimizeTvmStorage) { addrHash = addrHash(address); this.address = address; this.store = store; + this.optimizeTvmStorage = optimizeTvmStorage; + this.aliasCheckEnabled = ForkController.instance().pass(ForkBlockVersionEnum.VERSION_4_8_2_3); } public Storage(Storage storage) { @@ -37,10 +52,16 @@ public Storage(Storage storage) { this.address = storage.getAddress().clone(); this.store = storage.store; this.contractVersion = storage.contractVersion; - storage.getRowCache().forEach((DataWord rowKey, StorageRowCapsule row) -> { + this.optimizeTvmStorage = storage.optimizeTvmStorage; + this.aliasCheckEnabled = storage.aliasCheckEnabled; + storage.getRowCache().forEach((DataWord key, StorageRowCapsule row) -> { StorageRowCapsule newRow = new StorageRowCapsule(row); - this.rowCache.put(rowKey.clone(), newRow); + this.rowCache.put(key.clone(), newRow); }); + storage.oldRowKeyOwners.forEach((DataWord legacy, DataWord owner) -> + this.oldRowKeyOwners.put(legacy.clone(), owner.clone())); + storage.readKinds.forEach((DataWord key, ReadKind kind) -> + this.readKinds.put(key.clone(), kind)); } private byte[] compose(byte[] key, byte[] addrHash) { @@ -53,6 +74,18 @@ private byte[] compose(byte[] key, byte[] addrHash) { return result; } + private byte[] getOldRowKey(DataWord key) { + return compose(key.getData(), addrHash); + } + + private byte[] getNewRowKey(DataWord key) { + byte[] result = new byte[PREFIX_BYTES + WORD_BYTES]; + arraycopy(addrHash, 0, result, 0, PREFIX_BYTES); + arraycopy(Hash.sha3(ByteUtil.merge(addrHash, key.getData())), 0, result, PREFIX_BYTES, + WORD_BYTES); + return result; + } + // 32 bytes private static byte[] addrHash(byte[] address) { return Hash.sha3(address); @@ -71,6 +104,12 @@ public void generateAddrHash(byte[] trxId) { } public DataWord getValue(DataWord key) { + if (optimizeTvmStorage) { + return getOptimized(key); + } + if (aliasCheckEnabled) { + checkAlias(key); + } if (rowCache.containsKey(key)) { return new DataWord(rowCache.get(key).getValue()); } else { @@ -84,17 +123,88 @@ public DataWord getValue(DataWord key) { } public void put(DataWord key, DataWord value) { + if (!optimizeTvmStorage && aliasCheckEnabled) { + checkAlias(key); + } if (rowCache.containsKey(key)) { rowCache.get(key).setValue(value.getData()); } else { - byte[] rowKey = compose(key.getData(), addrHash); + byte[] rowKey = optimizeTvmStorage ? getNewRowKey(key) : getOldRowKey(key); StorageRowCapsule row = new StorageRowCapsule(rowKey, value.getData()); rowCache.put(key, row); } + if (optimizeTvmStorage) { + ownOldKey(key); + } + } + + private DataWord getOptimized(DataWord key) { + if (rowCache.containsKey(key)) { + return new DataWord(rowCache.get(key).getValue()); + } + if (readKinds.get(key) == ReadKind.EMPTY + || readKinds.get(key) == ReadKind.NEW) { + return null; + } + + byte[] newRowKey = getNewRowKey(key); + StorageRowCapsule newRow = store.get(newRowKey); + if (newRow != null && newRow.getValue() != null) { + readKinds.put(key.clone(), ReadKind.NEW); + if (DataWord.isZero(newRow.getValue())) { + return null; + } + return cacheRead(key, newRowKey, newRow.getValue()); + } + + if (oldKeyTaken(key)) { + return null; + } + + byte[] oldRowKey = getOldRowKey(key); + StorageRowCapsule oldRow = store.get(oldRowKey); + if (oldRow != null && oldRow.getValue() != null) { + readKinds.put(key.clone(), ReadKind.OLD); + return cacheRead(key, oldRowKey, oldRow.getValue()); + } + + readKinds.put(key.clone(), ReadKind.EMPTY); + return null; + } + + private DataWord cacheRead(DataWord key, byte[] rowKey, byte[] value) { + StorageRowCapsule row = new StorageRowCapsule(value.clone()); + row.setRowKey(rowKey); + rowCache.put(key, row); + ownOldKey(key); + return new DataWord(row.getValue()); + } + + private void checkAlias(DataWord key) { + DataWord oldRowKey = new DataWord(getOldRowKey(key)); + DataWord owner = oldRowKeyOwners.get(oldRowKey); + if (owner == null) { + oldRowKeyOwners.put(oldRowKey, key.clone()); + } else if (!owner.equals(key)) { + throw new Program.OutOfTimeException("CPU timeout for storage check"); + } + } + + private void ownOldKey(DataWord key) { + oldRowKeyOwners.putIfAbsent(new DataWord(getOldRowKey(key)), key.clone()); + } + + private boolean oldKeyTaken(DataWord key) { + DataWord owner = oldRowKeyOwners.get(new DataWord(getOldRowKey(key))); + return owner != null && !owner.equals(key); } public void commit() { - rowCache.forEach((DataWord rowKey, StorageRowCapsule row) -> { + if (optimizeTvmStorage) { + commitOptimized(); + return; + } + rowCache.forEach((DataWord key, StorageRowCapsule row) -> { if (row.isDirty()) { if (new DataWord(row.getValue()).isZero()) { this.store.delete(row.getRowKey()); @@ -104,4 +214,32 @@ public void commit() { } }); } + + private void commitOptimized() { + rowCache.forEach((DataWord key, StorageRowCapsule row) -> { + if (!row.isDirty()) { + return; + } + putNew(key, row.getValue()); + ReadKind kind = readKinds.get(key); + if (kind == null || kind == ReadKind.OLD) { + store.delete(getOldRowKey(key)); + } + }); + readKinds.forEach((DataWord key, ReadKind kind) -> { + StorageRowCapsule row = rowCache.get(key); + if (row != null && row.isDirty()) { + return; + } + if (kind == ReadKind.OLD) { + putNew(key, row.getValue()); + store.delete(getOldRowKey(key)); + } + }); + } + + private void putNew(DataWord key, byte[] value) { + store.put(getNewRowKey(key), new StorageRowCapsule(value)); + } + } diff --git a/actuator/src/main/java/org/tron/core/vm/repository/Repository.java b/actuator/src/main/java/org/tron/core/vm/repository/Repository.java index 8f91d59d0b8..ab86328c428 100644 --- a/actuator/src/main/java/org/tron/core/vm/repository/Repository.java +++ b/actuator/src/main/java/org/tron/core/vm/repository/Repository.java @@ -59,6 +59,10 @@ public interface Repository { boolean isNewContract(byte[] address); + void markSelfDestruct(byte[] address); + + boolean isSelfDestructed(byte[] address); + void updateAccount(byte[] address, AccountCapsule accountCapsule); void updateDynamicProperty(byte[] word, BytesCapsule bytesCapsule); diff --git a/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java b/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java index 62e7ce6ec08..d629f1473bb 100644 --- a/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java +++ b/actuator/src/main/java/org/tron/core/vm/repository/RepositoryImpl.java @@ -139,6 +139,7 @@ public class RepositoryImpl implements Repository { private final HashMap> delegatedResourceAccountIndexCache = new HashMap<>(); private final HashBasedTable> transientStorage = HashBasedTable.create(); private final HashSet newContractCache = new HashSet<>(); + private final HashSet selfDestructCache = new HashSet<>(); public static void removeLruCache(byte[] address) { } @@ -572,6 +573,29 @@ public boolean isNewContract(byte[] address) { } } + @Override + public void markSelfDestruct(byte[] address) { + selfDestructCache.add(Key.create(address)); + } + + @Override + public boolean isSelfDestructed(byte[] address) { + Key key = Key.create(address); + if (selfDestructCache.contains(key)) { + return true; + } + + if (parent != null) { + boolean isSelfDestructed = parent.isSelfDestructed(address); + if (isSelfDestructed) { + selfDestructCache.add(key); + } + return isSelfDestructed; + } else { + return false; + } + } + @Override public void updateAccount(byte[] address, AccountCapsule accountCapsule) { accountCache.put(Key.create(address), @@ -715,7 +739,8 @@ public Storage getStorage(byte[] address) { storage = parentStorage; } } else { - storage = new Storage(address, getStorageRowStore()); + storage = new Storage(address, getStorageRowStore(), + VMConfig.allowOptimizeTvmStorage()); } ContractCapsule contract = getContract(address); if (contract != null) { @@ -780,6 +805,7 @@ public void commit() { commitDelegatedResourceAccountIndexCache(repository); commitTransientStorage(repository); commitNewContractCache(repository); + commitSelfDestructCache(repository); } @Override @@ -924,7 +950,6 @@ private long increase(long lastUsage, long usage, long lastTime, long now, long } if (lastTime != now) { - assert now > lastTime; if (lastTime + windowSize > now) { long delta = now - lastTime; double decay = (windowSize - delta) / (double) windowSize; @@ -973,8 +998,6 @@ public long calculateGlobalEnergyLimit(AccountCapsule accountCapsule) { long totalEnergyLimit = getDynamicPropertiesStore().getTotalEnergyCurrentLimit(); long totalEnergyWeight = getDynamicPropertiesStore().getTotalEnergyWeight(); - assert totalEnergyWeight > 0; - if (hardenResourceCalculation()) { return BigInteger.valueOf(energyWeight) .multiply(BigInteger.valueOf(totalEnergyLimit)) @@ -1142,6 +1165,12 @@ public void commitNewContractCache(Repository deposit) { } } + private void commitSelfDestructCache(Repository deposit) { + if (deposit != null) { + selfDestructCache.forEach(key -> deposit.markSelfDestruct(key.getData())); + } + } + /** * Get the block id from the number. */ diff --git a/actuator/src/main/java/org/tron/core/vm/utils/MUtil.java b/actuator/src/main/java/org/tron/core/vm/utils/MUtil.java index e07360e6863..c7059016b88 100644 --- a/actuator/src/main/java/org/tron/core/vm/utils/MUtil.java +++ b/actuator/src/main/java/org/tron/core/vm/utils/MUtil.java @@ -59,6 +59,12 @@ public static boolean isNotNullOrEmpty(String str) { return !isNullOrEmpty(str); } + public static void checkCPUTimeForContractHashFields() { + if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2)) { + throw new OutOfTimeException("CPU timeout for contract hash fields"); + } + } + public static void checkCPUTime() { if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_7_1)) { throw new OutOfTimeException("CPU timeout for 0x0a executing"); @@ -76,4 +82,23 @@ public static void checkCPUTimeForModExp() { throw new OutOfTimeException("CPU timeout for modExp executing"); } } + + public static void checkCPUTimeForFreezeV2AfterSelfDestruct() { + if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2)) { + throw new OutOfTimeException("CPU timeout for FreezeBalanceV2 after SELFDESTRUCT"); + } + } + + public static void checkCPUTimeForSelfDestructedBeneficiary() { + if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2)) { + throw new OutOfTimeException( + "CPU timeout for SELFDESTRUCT with selfdestructed beneficiary"); + } + } + + public static void checkCPUTimeForInvalidDelegatedV2Balance() { + if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2)) { + throw new OutOfTimeException("CPU timeout for invalid delegated V2 balance"); + } + } } diff --git a/actuator/src/test/java/org/tron/core/vm/Bn128PairingTimeoutForkTest.java b/actuator/src/test/java/org/tron/core/vm/Bn128PairingTimeoutForkTest.java new file mode 100644 index 00000000000..2bb4c2f6db1 --- /dev/null +++ b/actuator/src/test/java/org/tron/core/vm/Bn128PairingTimeoutForkTest.java @@ -0,0 +1,54 @@ +package org.tron.core.vm; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertThrows; + +import java.math.BigInteger; +import org.apache.commons.lang3.tuple.Pair; +import org.junit.Test; +import org.tron.core.vm.program.Program.OutOfTimeException; + +public class Bn128PairingTimeoutForkTest { + + @Test + public void expiredDeadlineTimesOut() { + PrecompiledContracts.BN128Pairing pairing = pairing(0); + assertThrows(OutOfTimeException.class, () -> pairing.execute(onePair())); + } + + @Test + public void futureDeadlineReturnsPairingResult() { + PrecompiledContracts.BN128Pairing pairing = pairing(Long.MAX_VALUE / 1000); + Pair out = pairing.execute(onePair()); + assertTrue(out.getLeft()); + assertEquals(32, out.getRight().length); + } + + private static PrecompiledContracts.BN128Pairing pairing(long vmShouldEndInUs) { + PrecompiledContracts.BN128Pairing pairing = new PrecompiledContracts.BN128Pairing(); + pairing.setVmShouldEndInUs(vmShouldEndInUs); + return pairing; + } + + private static byte[] onePair() { + byte[] input = new byte[192]; + write(input, 0, BigInteger.ONE); + write(input, 32, BigInteger.valueOf(2)); + write(input, 64, new BigInteger( + "11559732032986387107991004021392285783925812861821192530917403151452391805634")); + write(input, 96, new BigInteger( + "10857046999023057135944570762232829481370756359578518086990519993285655852781")); + write(input, 128, new BigInteger( + "4082367875863433681332203403145435568316851327593401208105741076214120093531")); + write(input, 160, new BigInteger( + "8495653923123431417604973247489272438418190587263600148770280649306958101930")); + return input; + } + + private static void write(byte[] dest, int offset, BigInteger value) { + byte[] raw = value.toByteArray(); + int src = raw.length > 32 ? raw.length - 32 : 0; + System.arraycopy(raw, src, dest, offset + 32 - (raw.length - src), raw.length - src); + } +} diff --git a/actuator/src/test/java/org/tron/core/vm/program/StorageAliasTest.java b/actuator/src/test/java/org/tron/core/vm/program/StorageAliasTest.java new file mode 100644 index 00000000000..e24f1a691f9 --- /dev/null +++ b/actuator/src/test/java/org/tron/core/vm/program/StorageAliasTest.java @@ -0,0 +1,372 @@ +package org.tron.core.vm.program; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockedStatic; +import org.tron.common.runtime.vm.DataWord; +import org.tron.common.utils.ForkController; +import org.tron.core.capsule.StorageRowCapsule; +import org.tron.core.config.Parameter.ForkBlockVersionEnum; +import org.tron.core.store.StorageRowStore; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.program.Program.OutOfTimeException; + +public class StorageAliasTest { + + private ForkController controller; + private MockedStatic fork; + private StorageRowStore store; + private Storage storage; + private final DataWord slot = new DataWord(1); + private final DataWord alias = aliasedSlot(1); + + @Before + public void setUp() { + controller = mock(ForkController.class); + fork = mockStatic(ForkController.class); + fork.when(ForkController::instance).thenReturn(controller); + when(controller.pass(ForkBlockVersionEnum.VERSION_4_8_2_3)).thenReturn(true); + VMConfig.setLocalSnapshot(new VMConfig.Snapshot()); + store = mock(StorageRowStore.class); + storage = new Storage(new byte[21], store, false); + } + + @After + public void tearDown() { + VMConfig.clearLocalSnapshot(); + fork.close(); + } + + @Test + public void repeatedWritesIncludingZeroDoNotAlias() { + storage.put(slot, new DataWord(5)); + storage.put(slot.clone(), DataWord.ZERO()); + storage.put(slot.clone(), new DataWord(7)); + assertEquals(new DataWord(7), storage.getValue(slot)); + assertThrows(OutOfTimeException.class, () -> storage.put(alias, new DataWord(8))); + } + + @Test + public void readOfAliasThrowsAndSameSlotReadWriteStillWorks() { + when(store.get(argThat(key -> key != null && key.length == 32))).thenAnswer( + invocation -> new StorageRowCapsule(new DataWord(5).getData())); + assertEquals(new DataWord(5), storage.getValue(slot)); + assertEquals(new DataWord(5), storage.getValue(slot.clone())); + assertThrows(OutOfTimeException.class, () -> storage.getValue(alias)); + storage.put(slot, DataWord.ZERO()); + assertEquals(DataWord.ZERO(), storage.getValue(slot)); + assertThrows(OutOfTimeException.class, () -> storage.put(alias, new DataWord(8))); + } + + @Test + public void readOfAliasAfterWriteThrows() { + when(store.get(argThat(key -> key != null && key.length == 32))).thenAnswer( + invocation -> new StorageRowCapsule(new DataWord(5).getData())); + storage.put(slot, new DataWord(9)); + assertThrows(OutOfTimeException.class, () -> storage.getValue(alias)); + assertEquals(new DataWord(9), storage.getValue(slot)); + } + + @Test + public void aliasedReadsRemainAllowedBeforeFork() { + when(controller.pass(ForkBlockVersionEnum.VERSION_4_8_2_3)).thenReturn(false); + Storage before = new Storage(new byte[21], store, false); + when(store.get(any(byte[].class))).thenAnswer( + invocation -> new StorageRowCapsule(new DataWord(5).getData())); + assertEquals(new DataWord(5), before.getValue(slot)); + assertEquals(new DataWord(5), before.getValue(alias)); + before.put(alias, new DataWord(8)); + assertEquals(new DataWord(8), before.getValue(alias)); + } + + @Test + public void forkFlagIsCapturedOnceAtConstruction() { + clearInvocations(controller); + when(controller.pass(ForkBlockVersionEnum.VERSION_4_8_2_3)).thenReturn(false); + Storage before = new Storage(new byte[21], store, false); + before.put(slot, new DataWord(5)); + + when(controller.pass(ForkBlockVersionEnum.VERSION_4_8_2_3)).thenReturn(true); + before.put(alias, new DataWord(8)); + assertEquals(new DataWord(8), before.getValue(alias)); + Storage child = new Storage(before); + child.put(slot, new DataWord(1)); + child.put(alias, new DataWord(2)); + verify(controller, times(1)).pass(ForkBlockVersionEnum.VERSION_4_8_2_3); + + Storage after = new Storage(new byte[21], store, false); + after.put(alias, new DataWord(8)); + assertThrows(OutOfTimeException.class, () -> after.put(slot, new DataWord(7))); + verify(controller, times(2)).pass(ForkBlockVersionEnum.VERSION_4_8_2_3); + + clearInvocations(controller); + Storage optimized = new Storage(new byte[21], store, true); + optimized.put(slot, new DataWord(1)); + optimized.put(alias, new DataWord(2)); + assertEquals(new DataWord(2), optimized.getValue(alias)); + verify(controller, times(1)).pass(ForkBlockVersionEnum.VERSION_4_8_2_3); + } + + @Test + public void aliasedWritesRemainAllowedBeforeFork() { + when(controller.pass(ForkBlockVersionEnum.VERSION_4_8_2_3)).thenReturn(false); + Storage before = new Storage(new byte[21], store, false); + before.put(slot, new DataWord(5)); + before.put(alias, new DataWord(8)); + assertEquals(new DataWord(5), before.getValue(slot)); + assertEquals(new DataWord(8), before.getValue(alias)); + } + + @Test + public void copyInheritsWrittenRowsAndAllowsRepeatedWrites() { + storage.put(slot, new DataWord(5)); + Storage child = new Storage(storage); + assertThrows(OutOfTimeException.class, () -> child.put(alias, new DataWord(8))); + child.put(slot.clone(), new DataWord(7)); + assertEquals(new DataWord(7), child.getValue(slot)); + assertEquals(new DataWord(5), storage.getValue(slot)); + } + + @Test + public void discardedChildDoesNotLeakWrittenRows() { + Storage child = new Storage(storage); + child.put(slot, new DataWord(5)); + storage.put(alias, new DataWord(8)); + assertEquals(new DataWord(8), storage.getValue(alias)); + assertEquals(new DataWord(5), child.getValue(slot)); + } + + @Test + public void versionOneUsesHashedLegacyRows() { + storage.setContractVersion(1); + storage.put(slot, new DataWord(5)); + storage.put(alias, new DataWord(8)); + assertFalse(Arrays.equals(storage.getRowCache().get(slot).getRowKey(), + storage.getRowCache().get(alias).getRowKey())); + assertEquals(new DataWord(5), storage.getValue(slot)); + assertEquals(new DataWord(8), storage.getValue(alias)); + } + + @Test + public void migratedNewKeysDoNotConflict() { + Storage optimized = new Storage(new byte[21], store, true); + when(store.get(argThat(key -> key != null && key.length == 48))) + .thenReturn(new StorageRowCapsule(new DataWord(4).getData())); + assertEquals(new DataWord(4), optimized.getValue(slot)); + assertEquals(new DataWord(4), optimized.getValue(alias)); + optimized.put(slot, new DataWord(5)); + optimized.put(alias, new DataWord(8)); + assertEquals(new DataWord(5), optimized.getValue(slot)); + assertEquals(new DataWord(8), optimized.getValue(alias)); + } + + @Test + public void optimizedWritesDoNotTimeoutAndCollidingReadIsEmpty() { + Storage optimized = new Storage(new byte[21], store, true); + when(store.get(argThat(key -> key != null && key.length == 32))) + .thenReturn(new StorageRowCapsule(new DataWord(7).getData())); + optimized.put(slot, new DataWord(5)); + assertNull(optimized.getValue(alias)); + optimized.put(alias, new DataWord(8)); + assertEquals(48, optimized.getRowCache().get(slot).getRowKey().length); + assertEquals(48, optimized.getRowCache().get(alias).getRowKey().length); + assertEquals(new DataWord(5), optimized.getValue(slot)); + assertEquals(new DataWord(8), optimized.getValue(alias)); + assertNull(optimized.getValue(anotherAlias())); + } + + @Test + public void oldKeyIsReturnedOnlyToTheFirstCachedSlot() { + Storage optimized = new Storage(new byte[21], store, true); + when(store.get(argThat(key -> key != null && key.length == 32))) + .thenReturn(new StorageRowCapsule(new DataWord(7).getData())); + assertEquals(new DataWord(7), optimized.getValue(slot)); + assertNull(optimized.getValue(alias)); + assertEquals(new DataWord(7), optimized.getValue(slot.clone())); + optimized.commit(); + verify(store, times(1)).put(argThat(key -> key != null && key.length == 48), + argThat(row -> new DataWord(row.getValue()).longValue() == 7L)); + verify(store).delete(argThat(key -> key != null && key.length == 32)); + } + + @Test + public void newKeyWinsOverACachedOldKeyCollision() { + Storage optimized = new Storage(new byte[21], store, true); + boolean[] serveNewKey = {true}; + when(store.get(any(byte[].class))).thenAnswer(invocation -> { + byte[] key = invocation.getArgument(0); + if (serveNewKey[0] && key.length == 48) { + return new StorageRowCapsule(new DataWord(4).getData()); + } + if (key.length == 32) { + return new StorageRowCapsule(new DataWord(7).getData()); + } + return null; + }); + assertEquals(new DataWord(4), optimized.getValue(slot)); + serveNewKey[0] = false; + assertNull(optimized.getValue(alias)); + serveNewKey[0] = true; + assertEquals(new DataWord(4), optimized.getValue(alias)); + } + + @Test + public void optimizedCommitDeletesLegacyKey() { + Storage optimized = new Storage(new byte[21], store, true); + optimized.put(slot, new DataWord(5)); + optimized.commit(); + verify(store).put(argThat(key -> key != null && key.length == 48), any()); + verify(store).delete(argThat(key -> key != null && key.length == 32)); + } + + @Test + public void readOfOldKeyMigratesOnCommit() { + Storage optimized = new Storage(new byte[21], store, true); + when(store.get(argThat(key -> key != null && key.length == 32))) + .thenReturn(new StorageRowCapsule(new DataWord(7).getData())); + assertEquals(new DataWord(7), optimized.getValue(slot)); + optimized.commit(); + verify(store).put(argThat(key -> key != null && key.length == 48), + argThat(row -> new DataWord(row.getValue()).longValue() == 7L)); + verify(store).delete(argThat(key -> key != null && key.length == 32)); + } + + @Test + public void readOfMissingKeyDoesNotWriteAndRepeatReadSkipsStore() { + Storage optimized = new Storage(new byte[21], store, true); + assertNull(optimized.getValue(slot)); + assertNull(optimized.getValue(slot)); + optimized.commit(); + verify(store, times(2)).get(any()); + verify(store, never()).put(any(), any()); + verify(store, never()).delete(any()); + } + + @Test + public void readOfNewKeyDoesNotRewrite() { + Storage optimized = new Storage(new byte[21], store, true); + when(store.get(argThat(key -> key != null && key.length == 48))) + .thenReturn(new StorageRowCapsule(new DataWord(4).getData())); + assertEquals(new DataWord(4), optimized.getValue(slot)); + optimized.commit(); + verify(store, never()).put(any(), any()); + verify(store, never()).delete(any()); + } + + @Test + public void writeAfterReadKeepsWrittenValueAndDeletesOldKey() { + Storage optimized = new Storage(new byte[21], store, true); + when(store.get(argThat(key -> key != null && key.length == 32))) + .thenReturn(new StorageRowCapsule(new DataWord(7).getData())); + assertEquals(new DataWord(7), optimized.getValue(slot)); + optimized.put(slot, new DataWord(9)); + optimized.commit(); + verify(store).put(argThat(key -> key != null && key.length == 48), + argThat(row -> new DataWord(row.getValue()).longValue() == 9L)); + verify(store).delete(argThat(key -> key != null && key.length == 32)); + } + + @Test + public void readThenWriteOfExistingNewKeyDoesNotDeleteOld() { + Storage optimized = new Storage(new byte[21], store, true); + when(store.get(argThat(key -> key != null && key.length == 48))) + .thenReturn(new StorageRowCapsule(new DataWord(4).getData())); + assertEquals(new DataWord(4), optimized.getValue(slot)); + optimized.put(slot, new DataWord(9)); + optimized.commit(); + verify(store).put(argThat(key -> key != null && key.length == 48), + argThat(row -> new DataWord(row.getValue()).longValue() == 9L)); + verify(store, never()).delete(any()); + } + + @Test + public void writeThenCacheHitDeletesOldKey() { + Storage optimized = new Storage(new byte[21], store, true); + when(store.get(argThat(key -> key != null && key.length == 48))) + .thenReturn(new StorageRowCapsule(new DataWord(4).getData())); + optimized.put(slot, new DataWord(9)); + assertEquals(new DataWord(9), optimized.getValue(slot)); + optimized.commit(); + verify(store).put(argThat(key -> key != null && key.length == 48), any()); + verify(store).delete(argThat(key -> key != null && key.length == 32)); + } + + @Test + public void storedZeroOnNewKeyReadsAsEmptyAndSkipsOldKey() { + Storage optimized = new Storage(new byte[21], store, true); + when(store.get(any(byte[].class))).thenAnswer(invocation -> { + byte[] key = invocation.getArgument(0); + if (key.length == 48) { + return new StorageRowCapsule(DataWord.ZERO().getData()); + } + if (key.length == 32) { + return new StorageRowCapsule(new DataWord(7).getData()); + } + return null; + }); + assertNull(optimized.getValue(slot)); + assertNull(optimized.getValue(slot)); + Storage child = new Storage(optimized); + assertNull(child.getValue(slot)); + verify(store, times(1)).get(argThat(key -> key != null && key.length == 48)); + verify(store, never()).get(argThat(key -> key != null && key.length == 32)); + optimized.commit(); + verify(store, never()).put(any(), any()); + verify(store, never()).delete(any()); + } + + @Test + public void writeAfterStoredZeroHitsCacheAndDoesNotDeleteOldKey() { + Storage optimized = new Storage(new byte[21], store, true); + when(store.get(argThat(key -> key != null && key.length == 48))) + .thenReturn(new StorageRowCapsule(DataWord.ZERO().getData())); + assertNull(optimized.getValue(slot)); + optimized.put(slot, new DataWord(9)); + assertEquals(new DataWord(9), optimized.getValue(slot)); + optimized.commit(); + verify(store, times(1)).get(any()); + verify(store).put(argThat(key -> key != null && key.length == 48), + argThat(row -> new DataWord(row.getValue()).longValue() == 9L)); + verify(store, never()).delete(any()); + } + + @Test + public void putZeroOverStoredZeroStaysInCache() { + Storage optimized = new Storage(new byte[21], store, true); + when(store.get(argThat(key -> key != null && key.length == 48))) + .thenReturn(new StorageRowCapsule(DataWord.ZERO().getData())); + assertNull(optimized.getValue(slot)); + optimized.put(slot, DataWord.ZERO()); + assertEquals(DataWord.ZERO(), optimized.getValue(slot)); + assertEquals(DataWord.ZERO(), optimized.getValue(slot.clone())); + verify(store, times(1)).get(any()); + } + + private static DataWord aliasedSlot(int value) { + byte[] bytes = new DataWord(value).getData().clone(); + bytes[15] = 1; + return new DataWord(bytes); + } + + private static DataWord anotherAlias() { + byte[] bytes = new DataWord(1).getData().clone(); + bytes[14] = 1; + return new DataWord(bytes); + } +} diff --git a/build.gradle b/build.gradle index 65e72c0fb73..7569c3bba32 100644 --- a/build.gradle +++ b/build.gradle @@ -6,7 +6,18 @@ plugins { } ext { - grpcVersion = "1.83.0" + grpcVersion = "1.83.1" + // Netty 4.2 split io.netty.handler.codec.protobuf out of netty-codec into its + // own artifact. Both :framework and :p2p put the varint32 framing codecs on + // their channel pipelines and so must declare it explicitly. Netty itself + // arrives transitively through grpc-netty, so this version has to move with + // grpcVersion above — keeping it here makes that coupling visible instead of + // leaving two literals to drift apart. + nettyVersion = "4.2.15.Final" + // Shared by :protocol and :p2p, which both generate from .proto files. + protobufVersion = "3.25.8" + // Shared by :framework, :plugins and :p2p. + checkstyleVersion = "8.7" } allprojects { @@ -91,16 +102,14 @@ subprojects { } dependencies { - implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.36' - implementation group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.36' - implementation group: 'org.slf4j', name: 'jul-to-slf4j', version: '1.7.36' - implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.13' + implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.17' + implementation group: 'org.slf4j', name: 'jcl-over-slf4j', version: '2.0.17' + implementation group: 'org.slf4j', name: 'jul-to-slf4j', version: '2.0.17' + implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.3.16' implementation "com.google.code.findbugs:jsr305:3.0.0" implementation group: 'org.springframework', name: 'spring-context', version: "${springVersion}" - implementation "org.apache.commons:commons-lang3:3.4" - implementation group: 'org.apache.commons', name: 'commons-math', version: '2.2' - implementation "org.apache.commons:commons-collections4:4.1" - implementation group: 'joda-time', name: 'joda-time', version: '2.3' + implementation "org.apache.commons:commons-lang3:3.20.0" + implementation "org.apache.commons:commons-collections4:4.6.0" implementation group: 'org.bouncycastle', name: 'bcprov-jdk18on', version: '1.84' compileOnly 'org.projectlombok:lombok:1.18.34' diff --git a/chainbase/src/main/java/org/tron/common/utils/ForkUtils.java b/chainbase/src/main/java/org/tron/common/utils/ForkUtils.java deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/chainbase/src/main/java/org/tron/common/zksnark/MerklePath.java b/chainbase/src/main/java/org/tron/common/zksnark/MerklePath.java index 96d6ceac893..7beba9f9eff 100644 --- a/chainbase/src/main/java/org/tron/common/zksnark/MerklePath.java +++ b/chainbase/src/main/java/org/tron/common/zksnark/MerklePath.java @@ -75,7 +75,6 @@ private static long convertVectorToLong(List v) throws ZksnarkException } public byte[] encode() throws ZksnarkException { - assert (authenticationPath.size() == index.size()); List> pathByteList = Lists.newArrayList(); long indexLong; // 64 for (int i = 0; i < authenticationPath.size(); i++) { diff --git a/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java index 1af7b55c8b2..026dce74ec8 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java @@ -1336,6 +1336,10 @@ public void clearDelegatedResource() { this.account = builder.build(); } + public boolean hasInvalidDelegatedV2() { + return getDelegatedFrozenV2BalanceForBandwidth() < 0 || getDelegatedFrozenV2BalanceForEnergy() < 0; + } + public void importAsset(byte[] key) { this.account = AssetUtil.importAsset(this.account, key); } diff --git a/chainbase/src/main/java/org/tron/core/config/args/Parameter.java b/chainbase/src/main/java/org/tron/core/config/args/Parameter.java deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/chainbase/src/main/java/org/tron/core/db/EnergyProcessor.java b/chainbase/src/main/java/org/tron/core/db/EnergyProcessor.java index 0c429178636..267abbf06c4 100644 --- a/chainbase/src/main/java/org/tron/core/db/EnergyProcessor.java +++ b/chainbase/src/main/java/org/tron/core/db/EnergyProcessor.java @@ -155,8 +155,6 @@ public long calculateGlobalEnergyLimit(AccountCapsule accountCapsule) { long totalEnergyWeight = dynamicPropertiesStore.getTotalEnergyWeight(); if (dynamicPropertiesStore.allowNewReward() && totalEnergyWeight <= 0) { return 0; - } else { - assert totalEnergyWeight > 0; } if (hardenCalculation()) { return calculateGlobalLimitV1(frozeBalance, totalEnergyLimit, totalEnergyWeight); @@ -205,4 +203,3 @@ private long scaleByRate(long value, long numerator, long denominator) { } } - diff --git a/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java b/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java index 6706c430084..8b6f96504ec 100644 --- a/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java +++ b/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java @@ -63,7 +63,6 @@ protected long increase(long lastUsage, long usage, long lastTime, long now, lon } if (lastTime != now) { - assert now > lastTime; if (lastTime + windowSize > now) { long delta = now - lastTime; double decay = (windowSize - delta) / (double) windowSize; diff --git a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java index 0f74f20d379..cc7cdbd9fa3 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -12,13 +12,13 @@ import java.util.stream.IntStream; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.Time; import org.tron.core.capsule.BytesCapsule; import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.db.TronStoreWithRevoking; @@ -258,6 +258,8 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking private static final byte[] TURKISH_KEY_MIGRATION_DONE = "TURKISH_KEY_MIGRATION_DONE".getBytes(); + private static final byte[] ALLOW_OPTIMIZE_TVM_STORAGE = "ALLOW_OPTIMIZE_TVM_STORAGE".getBytes(); + @Autowired private DynamicPropertiesStore(@Value("properties") String dbName) { super(dbName); @@ -2261,8 +2263,8 @@ public void updateNextMaintenanceTime(long blockTime) { logger.info( "Do update nextMaintenanceTime, currentMaintenanceTime: {}, blockTime: {}, " + "nextMaintenanceTime: {}.", - new DateTime(currentMaintenanceTime), new DateTime(blockTime), - new DateTime(nextMaintenanceTime) + Time.getIsoTimeString(currentMaintenanceTime), Time.getIsoTimeString(blockTime), + Time.getIsoTimeString(nextMaintenanceTime) ); } @@ -3083,6 +3085,21 @@ public long getTurkishKeyMigrationDone() { .orElse(0L); } + public long getAllowOptimizeTvmStorage() { + return Optional.ofNullable(getUnchecked(ALLOW_OPTIMIZE_TVM_STORAGE)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(0L); + } + + public void saveAllowOptimizeTvmStorage(long value) { + this.put(ALLOW_OPTIMIZE_TVM_STORAGE, new BytesCapsule(ByteArray.fromLong(value))); + } + + public boolean allowOptimizeTvmStorage() { + return getAllowOptimizeTvmStorage() == 1L; + } + private static class DynamicResourceProperties { private static final byte[] ONE_DAY_NET_LIMIT = "ONE_DAY_NET_LIMIT".getBytes(); diff --git a/common/build.gradle b/common/build.gradle index 14d3eb4e637..7d8922aab5c 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -8,7 +8,9 @@ sourceCompatibility = 1.8 dependencies { - api group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.18.6' // https://github.com/FasterXML/jackson-databind/issues/3627 + // avoid x.y.z.w micro-patches, they may ship broken Gradle module metadata: + // https://github.com/FasterXML/jackson-databind/issues/3627 + api group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.18.10' api "com.cedarsoftware:java-util:3.2.0" api group: 'org.apache.httpcomponents', name: 'httpasyncclient', version: '4.1.1' api group: 'commons-codec', name: 'commons-codec', version: '1.11' @@ -21,23 +23,7 @@ dependencies { api 'org.aspectj:aspectjrt:1.9.8' api 'org.aspectj:aspectjweaver:1.9.8' api 'org.aspectj:aspectjtools:1.9.8' - api group: 'io.github.tronprotocol', name: 'libp2p', version: '2.2.9',{ - exclude group: 'io.grpc', module: 'grpc-context' - exclude group: 'io.grpc', module: 'grpc-core' - exclude group: 'io.grpc', module: 'grpc-netty' - exclude group: 'com.google.protobuf', module: 'protobuf-java' - exclude group: 'com.google.protobuf', module: 'protobuf-java-util' - // https://github.com/dom4j/dom4j/pull/116 - // https://github.com/gradle/gradle/issues/13656 - // https://github.com/dom4j/dom4j/issues/99 - exclude group: 'jaxen', module: 'jaxen' - exclude group: 'javax.xml.stream', module: 'stax-api' - exclude group: 'net.java.dev.msv', module: 'xsdlib' - exclude group: 'pull-parser', module: 'pull-parser' - exclude group: 'xpp3', module: 'xpp3' - exclude group: 'org.bouncycastle', module: 'bcprov-jdk18on' - exclude group: 'org.bouncycastle', module: 'bcutil-jdk18on' - } + api project(":p2p") api project(":protocol") api project(":platform") } diff --git a/common/src/main/java/org/tron/common/entity/NodeInfo.java b/common/src/main/java/org/tron/common/entity/NodeInfo.java index 4b23bd185e3..6f53b3935b8 100644 --- a/common/src/main/java/org/tron/common/entity/NodeInfo.java +++ b/common/src/main/java/org/tron/common/entity/NodeInfo.java @@ -146,7 +146,7 @@ public Protocol.NodeInfo transferToProtoEntity() { peerInfoBuilder.setLastBlockUpdateTime(peerInfo.getLastBlockUpdateTime()); peerInfoBuilder.setSyncFlag(peerInfo.isSyncFlag()); peerInfoBuilder.setHeadBlockTimeWeBothHave(peerInfo.getHeadBlockTimeWeBothHave()); - peerInfoBuilder.setNeedSyncFromPeer(peerInfo.isSyncFlag()); + peerInfoBuilder.setNeedSyncFromPeer(peerInfo.isNeedSyncFromPeer()); peerInfoBuilder.setNeedSyncFromUs(peerInfo.isNeedSyncFromUs()); peerInfoBuilder.setHost(peerInfo.getHost()); peerInfoBuilder.setPort(peerInfo.getPort()); diff --git a/common/src/main/java/org/tron/common/logsfilter/TriggerConfig.java b/common/src/main/java/org/tron/common/logsfilter/TriggerConfig.java index d76db47c40d..bf4b1cd4946 100644 --- a/common/src/main/java/org/tron/common/logsfilter/TriggerConfig.java +++ b/common/src/main/java/org/tron/common/logsfilter/TriggerConfig.java @@ -33,7 +33,7 @@ public TriggerConfig() { triggerName = ""; enabled = false; topic = ""; - redundancy = false; // event will also write to log + redundancy = false; // if true, event triggers will also be emitted as log triggers ethCompatible = false; // add eth compatible fields, just for transaction now solidified = false; // just write solidified data, just for block and transaction now } diff --git a/common/src/main/java/org/tron/common/parameter/CommonParameter.java b/common/src/main/java/org/tron/common/parameter/CommonParameter.java index eeb92fdbd60..3f1b623fca1 100644 --- a/common/src/main/java/org/tron/common/parameter/CommonParameter.java +++ b/common/src/main/java/org/tron/common/parameter/CommonParameter.java @@ -295,9 +295,6 @@ public class CommonParameter { public String trustNodeAddr; // clearParam: "" @Getter @Setter - public boolean walletExtensionApi; - @Getter - @Setter public boolean estimateEnergy; @Getter @Setter diff --git a/common/src/main/java/org/tron/common/setting/RocksDbSettings.java b/common/src/main/java/org/tron/common/setting/RocksDbSettings.java index d5df5e261b5..8696092a0a0 100644 --- a/common/src/main/java/org/tron/common/setting/RocksDbSettings.java +++ b/common/src/main/java/org/tron/common/setting/RocksDbSettings.java @@ -6,7 +6,6 @@ import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.rocksdb.BlockBasedTableConfig; -import org.rocksdb.BloomFilter; import org.rocksdb.ComparatorOptions; import org.rocksdb.InfoLogLevel; import org.rocksdb.LRUCache; @@ -211,13 +210,7 @@ protected void log(InfoLogLevel infoLogLevel, String logMsg) { options.setTargetFileSizeBase(settings.getTargetFileSizeBase()); // table options - final BlockBasedTableConfig tableCfg; - options.setTableFormatConfig(tableCfg = new BlockBasedTableConfig()); - tableCfg.setBlockSize(settings.getBlockSize()); - tableCfg.setBlockCache(RocksDbSettings.getCache()); - tableCfg.setCacheIndexAndFilterBlocks(true); - tableCfg.setPinL0FilterAndIndexBlocksInCache(true); - tableCfg.setFilter(new BloomFilter(10, false)); + options.setTableFormatConfig(new BlockBasedTableConfig()); if (Constant.MARKET_PAIR_PRICE_TO_ORDER.equals(dbName)) { ComparatorOptions comparatorOptions = new ComparatorOptions(); options.setComparator(new MarketOrderPriceComparatorForRocksDB(comparatorOptions)); diff --git a/common/src/main/java/org/tron/common/utils/Time.java b/common/src/main/java/org/tron/common/utils/Time.java index fdbfcb5f283..15e9d3d4b55 100644 --- a/common/src/main/java/org/tron/common/utils/Time.java +++ b/common/src/main/java/org/tron/common/utils/Time.java @@ -1,9 +1,17 @@ package org.tron.common.utils; import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; public class Time { + // Matches joda-time's DateTime.toString() output, byte for byte: fixed + // 3-digit millis, offset as +08:00, and Z when the system zone is UTC. + private static final DateTimeFormatter ISO_MILLIS_FORMAT = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + public static long getCurrentMillis() { return System.currentTimeMillis(); } @@ -11,4 +19,8 @@ public static long getCurrentMillis() { public static String getTimeString(long time) { return new Timestamp(time).toString(); } + + public static String getIsoTimeString(long time) { + return Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault()).format(ISO_MILLIS_FORMAT); + } } diff --git a/common/src/main/java/org/tron/core/config/Parameter.java b/common/src/main/java/org/tron/core/config/Parameter.java index 233f1d9ef7a..57954f2add4 100644 --- a/common/src/main/java/org/tron/core/config/Parameter.java +++ b/common/src/main/java/org/tron/core/config/Parameter.java @@ -30,7 +30,9 @@ public enum ForkBlockVersionEnum { VERSION_4_8_0_1(33, 1596780000000L, 70), VERSION_4_8_1(34, 1596780000000L, 80), VERSION_4_8_1_1(35, 1596780000000L, 70), - VERSION_4_8_2(36, 1596780000000L, 80); + VERSION_4_8_2(36, 1596780000000L, 80), + VERSION_4_8_2_2(37, 1596780000000L, 70), + VERSION_4_8_2_3(38, 1596780000000L, 70); // if add a version, modify BLOCK_VERSION simultaneously @Getter @@ -79,7 +81,7 @@ public class ChainConstant { public static final int SINGLE_REPEAT = 1; public static final int BLOCK_FILLED_SLOTS_NUMBER = 128; public static final int MAX_FROZEN_NUMBER = 1; - public static final int BLOCK_VERSION = 36; + public static final int BLOCK_VERSION = 38; public static final long FROZEN_PERIOD = 86_400_000L; public static final long DELEGATE_PERIOD = 3 * 86_400_000L; public static final long TRX_PRECISION = 1000_000L; diff --git a/common/src/main/java/org/tron/core/config/README.md b/common/src/main/java/org/tron/core/config/README.md index 5618cb9fed9..6bcd2ade1aa 100644 --- a/common/src/main/java/org/tron/core/config/README.md +++ b/common/src/main/java/org/tron/core/config/README.md @@ -20,7 +20,7 @@ storage { # block_KDB, peers, properties, recent-block, trans, # utxo, votes, witness, witness_schedule. - # Otherwise, db configs will remain defualt and data will be stored in + # Otherwise, db configs will remain default and data will be stored in # the path of "output-directory" or which is set by "-d" ("--output-directory"). # Attention: name is a required field that must be set !!! diff --git a/common/src/main/java/org/tron/core/config/args/CommitteeConfig.java b/common/src/main/java/org/tron/core/config/args/CommitteeConfig.java index 660fa289e3b..2696c220231 100644 --- a/common/src/main/java/org/tron/core/config/args/CommitteeConfig.java +++ b/common/src/main/java/org/tron/core/config/args/CommitteeConfig.java @@ -1,11 +1,14 @@ package org.tron.core.config.args; +import static org.tron.core.exception.TronError.ErrCode.PARAMETER_INIT; + import com.typesafe.config.Config; import com.typesafe.config.ConfigBeanFactory; import com.typesafe.config.ConfigValue; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; +import org.tron.core.exception.TronError; /** * Committee (governance) configuration bean. @@ -160,11 +163,11 @@ private void postProcess() { // cross-field: allowOldRewardOpt requires at least one reward/vote flag if (allowOldRewardOpt == 1 && allowNewRewardAlgorithm != 1 && allowNewReward != 1 && allowTvmVote != 1) { - throw new IllegalArgumentException( + throw new TronError( "At least one of the following proposals is required to be opened first: " + "committee.allowNewRewardAlgorithm = 1" + " or committee.allowNewReward = 1" - + " or committee.allowTvmVote = 1."); + + " or committee.allowTvmVote = 1.", PARAMETER_INIT); } } } diff --git a/common/src/main/java/org/tron/core/config/args/NodeConfig.java b/common/src/main/java/org/tron/core/config/args/NodeConfig.java index 91945b5a73b..9d3ae5449ae 100644 --- a/common/src/main/java/org/tron/core/config/args/NodeConfig.java +++ b/common/src/main/java/org/tron/core/config/args/NodeConfig.java @@ -26,7 +26,6 @@ public class NodeConfig { // ---- Flat scalar fields (auto-bound by ConfigBeanFactory) ---- private String trustNode = ""; - private boolean walletExtensionApi = false; private int syncFetchBatchNum = 2000; private int maxPendingBlockSize = 500; private int validateSignThreadNum = 0; // 0 = auto (availableProcessors) @@ -327,6 +326,12 @@ public static NodeConfig fromConfig(Config config) { nc.maxConnectionsWithSameIp = section.getInt("maxActiveNodesWithSameIp"); } + // node.walletExtensionApi (removed): the WalletExtension gRPC service no longer exists + if (section.hasPath("walletExtensionApi")) { + logger.warn("Configuring [node.walletExtensionApi] has been removed and is ignored. " + + "The WalletExtension gRPC service no longer exists."); + } + // Legacy key fallback: node.allowShieldedTransactionApi wins fullNodeAllowShieldedTransaction if (section.hasPath("allowShieldedTransactionApi")) { nc.allowShieldedTransactionApi = diff --git a/common/src/main/java/org/tron/core/vm/config/VMConfig.java b/common/src/main/java/org/tron/core/vm/config/VMConfig.java index 304ced33698..07b0bbe149e 100644 --- a/common/src/main/java/org/tron/core/vm/config/VMConfig.java +++ b/common/src/main/java/org/tron/core/vm/config/VMConfig.java @@ -8,8 +8,6 @@ */ public class VMConfig { - private static boolean vmTraceCompressed = false; - @Setter private static boolean vmTrace = false; @@ -46,6 +44,7 @@ public static class Snapshot { public boolean allowTvmSelfdestructRestriction; public boolean allowTvmOsaka; public boolean allowHardenResourceCalculation; + public boolean allowOptimizeTvmStorage; } // HEAD / block-processing config, written by the consensus path; read by everyone with no @@ -89,10 +88,6 @@ public static boolean vmTrace() { return vmTrace; } - public static boolean vmTraceCompressed() { - return vmTraceCompressed; - } - public static void initVmHardFork(boolean pass) { CommonParameter.ENERGY_LIMIT_HARD_FORK = pass; } @@ -204,6 +199,10 @@ public static void initAllowHardenResourceCalculation(long allow) { globalSnapshot.allowHardenResourceCalculation = allow == 1; } + public static void initAllowOptimizeTvmStorage(long allow) { + globalSnapshot.allowOptimizeTvmStorage = allow == 1; + } + public static boolean getEnergyLimitHardFork() { return CommonParameter.ENERGY_LIMIT_HARD_FORK; } @@ -311,4 +310,8 @@ public static boolean allowTvmOsaka() { public static boolean allowHardenResourceCalculation() { return current().allowHardenResourceCalculation; } + + public static boolean allowOptimizeTvmStorage() { + return current().allowOptimizeTvmStorage; + } } diff --git a/common/src/main/java/org/tron/json/JSON.java b/common/src/main/java/org/tron/json/JSON.java index ddab0af82a8..92e84c18057 100644 --- a/common/src/main/java/org/tron/json/JSON.java +++ b/common/src/main/java/org/tron/json/JSON.java @@ -22,42 +22,47 @@ @Deprecated public final class JSON { - static final ObjectMapper MAPPER = JsonMapper.builder(buildFactory()) - // Fastjson Feature.AllowUnQuotedFieldNames (default ON) - .enable(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES) - // Fastjson Feature.AllowSingleQuotes (default ON) - .enable(JsonReadFeature.ALLOW_SINGLE_QUOTES) - // Partial compatibility with Fastjson Feature.AllowArbitraryCommas: - // this only covers a single trailing comma like {"a":1,} or [1,2,]. - // Repeated/arbitrary commas like {"a":1,,,,} and [1,,2] remain rejected. - .enable(JsonReadFeature.ALLOW_TRAILING_COMMA) - // Fastjson accepts a leading plus sign for numbers (for example +123, +0.5) - .enable(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS) - // Partial compatibility for Fastjson's asymmetric decimal behavior: - // Fastjson accepts +.5 but rejects .5 by default. Jackson cannot model only - // the signed form, so enabling this also accepts .5. - .enable(JsonReadFeature.ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS) - // Fastjson accepts a trailing decimal point for numbers (for example 5.) - .enable(JsonReadFeature.ALLOW_TRAILING_DECIMAL_POINT_FOR_NUMBERS) - // Fastjson accepts leading zeros for numbers (for example 007) - .enable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS) - // Fastjson accepts unescaped control chars in strings (for example raw tab/newline) - .enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS) - // Fastjson accepts Java-style comments (// and /* */) - .enable(JsonReadFeature.ALLOW_JAVA_COMMENTS) - // Fastjson Feature.UseBigDecimal (default ON) - // https://github.com/alibaba/fastjson/wiki/deserialize_disable_bigdecimal_cn - .configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true) - // Fastjson Feature.IgnoreNotMatch (default ON) — unknown fields silently ignored - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - // Fastjson 1.x rejects non-comment tokens after the root value - .configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, true) - // Fastjson serializes empty beans as "{}" without error - .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) - // Fastjson omits null-valued fields by default (WriteMapNullValue is OFF by default) - // https://github.com/alibaba/fastjson/wiki/WriteNull_cn - .serializationInclusion(JsonInclude.Include.NON_NULL) - .build(); + static final ObjectMapper MAPPER = buildMapper(buildFactory()); + private static final ObjectMapper OUTBOUND_MAPPER = buildMapper(new JsonFactory()); + + private static ObjectMapper buildMapper(JsonFactory factory) { + return JsonMapper.builder(factory) + // Fastjson Feature.AllowUnQuotedFieldNames (default ON) + .enable(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES) + // Fastjson Feature.AllowSingleQuotes (default ON) + .enable(JsonReadFeature.ALLOW_SINGLE_QUOTES) + // Partial compatibility with Fastjson Feature.AllowArbitraryCommas: + // this only covers a single trailing comma like {"a":1,} or [1,2,]. + // Repeated/arbitrary commas like {"a":1,,,,} and [1,,2] remain rejected. + .enable(JsonReadFeature.ALLOW_TRAILING_COMMA) + // Fastjson accepts a leading plus sign for numbers (for example +123, +0.5) + .enable(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS) + // Partial compatibility for Fastjson's asymmetric decimal behavior: + // Fastjson accepts +.5 but rejects .5 by default. Jackson cannot model only + // the signed form, so enabling this also accepts .5. + .enable(JsonReadFeature.ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS) + // Fastjson accepts a trailing decimal point for numbers (for example 5.) + .enable(JsonReadFeature.ALLOW_TRAILING_DECIMAL_POINT_FOR_NUMBERS) + // Fastjson accepts leading zeros for numbers (for example 007) + .enable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS) + // Fastjson accepts unescaped control chars in strings (for example raw tab/newline) + .enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS) + // Fastjson accepts Java-style comments (// and /* */) + .enable(JsonReadFeature.ALLOW_JAVA_COMMENTS) + // Fastjson Feature.UseBigDecimal (default ON) + // https://github.com/alibaba/fastjson/wiki/deserialize_disable_bigdecimal_cn + .configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true) + // Fastjson Feature.IgnoreNotMatch (default ON) — unknown fields silently ignored + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + // Fastjson 1.x rejects non-comment tokens after the root value + .configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, true) + // Fastjson serializes empty beans as "{}" without error + .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) + // Fastjson omits null-valued fields by default (WriteMapNullValue is OFF by default) + // https://github.com/alibaba/fastjson/wiki/WriteNull_cn + .serializationInclusion(JsonInclude.Include.NON_NULL) + .build(); + } private static JsonFactory buildFactory() { return JsonFactory.builder().streamReadConstraints(StreamReadConstraints.builder() @@ -82,11 +87,15 @@ static boolean isNullLiteral(String text) { } public static JSONObject parseObject(String text) { + return parseObject(text, MAPPER); + } + + private static JSONObject parseObject(String text, ObjectMapper mapper) { if (isNullLiteral(text)) { return null; } try { - JsonNode node = MAPPER.readTree(text); + JsonNode node = mapper.readTree(text); if (node == null || node.isNull()) { return null; } @@ -101,6 +110,10 @@ public static JSONObject parseObject(String text) { } } + static JSONObject outboundParseObject(String text) { + return parseObject(text, OUTBOUND_MAPPER); + } + public static JsonNode parse(String text) { if (isNullLiteral(text)) { return null; diff --git a/common/src/main/java/org/tron/json/JSONObject.java b/common/src/main/java/org/tron/json/JSONObject.java index b96c8f6e420..07aaa7d4ceb 100644 --- a/common/src/main/java/org/tron/json/JSONObject.java +++ b/common/src/main/java/org/tron/json/JSONObject.java @@ -42,6 +42,14 @@ public static JSONObject parseObject(String text) { return JSON.parseObject(text); } + /** + * Parses internally generated outbound JSON with Jackson's default read constraints instead of + * the request limits. Use {@link #parseObject(String)} for external input. + */ + public static JSONObject outboundParseObject(String text) { + return JSON.outboundParseObject(text); + } + public boolean containsKey(String key) { return node.has(key); } diff --git a/common/src/main/resources/reference.conf b/common/src/main/resources/reference.conf index d8c483d932a..01d110208a0 100644 --- a/common/src/main/resources/reference.conf +++ b/common/src/main/resources/reference.conf @@ -108,7 +108,7 @@ storage { dbSettings = { levelNumber = 7 // Number of RocksDB levels. compactThreads = 0 // 0 = auto: max(availableProcessors, 1) - blocksize = 16 // n * KB + blocksize = 16 // n * KB. Currently retained for compatibility but not applied to native RocksDB table options. maxBytesForLevelBase = 256 // n * MB maxBytesForLevelMultiplier = 10 // Level size multiplier. level0FileNumCompactionTrigger = 2 // L0 files that trigger compaction. @@ -185,9 +185,6 @@ node { # Trust node for solidity node (example: "127.0.0.1:50051"). trustNode = "" - # Expose extension api to public or not - walletExtensionApi = false - listen.port = 18888 # P2P listen port. fetchBlock.timeout = 500 # Block fetch timeout (ms). diff --git a/common/src/test/java/org/tron/common/entity/NodeInfoTest.java b/common/src/test/java/org/tron/common/entity/NodeInfoTest.java new file mode 100644 index 00000000000..302fdb7b080 --- /dev/null +++ b/common/src/test/java/org/tron/common/entity/NodeInfoTest.java @@ -0,0 +1,58 @@ +package org.tron.common.entity; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.tron.protos.Protocol; + +public class NodeInfoTest { + + private PeerInfo newPeerInfo(boolean syncFlag, boolean needSyncFromPeer, + boolean needSyncFromUs) { + PeerInfo peerInfo = new PeerInfo(); + peerInfo.setSyncFlag(syncFlag); + peerInfo.setNeedSyncFromPeer(needSyncFromPeer); + peerInfo.setNeedSyncFromUs(needSyncFromUs); + // string fields must be non-null, otherwise the protobuf setters throw NPE + peerInfo.setLastSyncBlock(""); + peerInfo.setHost("127.0.0.1"); + peerInfo.setNodeId(""); + peerInfo.setHeadBlockWeBothHave(""); + peerInfo.setLocalDisconnectReason(""); + peerInfo.setRemoteDisconnectReason(""); + return peerInfo; + } + + /** + * The protobuf conversion must map each peer flag from its own source field. A previous + * copy-and-paste defect populated needSyncFromPeer from isSyncFlag(); distinct values for + * syncFlag and needSyncFromPeer are required so that such a mismatch is detected. + */ + @Test + public void testPeerFlagMappingIsIndependent() { + NodeInfo nodeInfo = new NodeInfo(); + nodeInfo.setBlock(""); + nodeInfo.setSolidityBlock(""); + List peerList = new ArrayList<>(); + // syncFlag != needSyncFromPeer so the two fields cannot be confused + peerList.add(newPeerInfo(false, true, false)); + peerList.add(newPeerInfo(true, false, true)); + nodeInfo.setPeerList(peerList); + nodeInfo.setCheatWitnessInfoMap(new java.util.HashMap<>()); + + Protocol.NodeInfo proto = nodeInfo.transferToProtoEntity(); + + Assert.assertEquals(2, proto.getPeerInfoListCount()); + + Protocol.NodeInfo.PeerInfo peer0 = proto.getPeerInfoList(0); + Assert.assertFalse(peer0.getSyncFlag()); + Assert.assertTrue(peer0.getNeedSyncFromPeer()); + Assert.assertFalse(peer0.getNeedSyncFromUs()); + + Protocol.NodeInfo.PeerInfo peer1 = proto.getPeerInfoList(1); + Assert.assertTrue(peer1.getSyncFlag()); + Assert.assertFalse(peer1.getNeedSyncFromPeer()); + Assert.assertTrue(peer1.getNeedSyncFromUs()); + } +} diff --git a/common/src/test/java/org/tron/common/setting/RocksDbSettingsTest.java b/common/src/test/java/org/tron/common/setting/RocksDbSettingsTest.java new file mode 100644 index 00000000000..44258df8255 --- /dev/null +++ b/common/src/test/java/org/tron/common/setting/RocksDbSettingsTest.java @@ -0,0 +1,59 @@ +/* + * java-tron is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * java-tron is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.tron.common.setting; + +import static org.junit.Assert.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.stream.Stream; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.rocksdb.Options; +import org.rocksdb.RocksDB; + +public class RocksDbSettingsTest { + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void shouldKeepNativeBlockTableDefaults() throws Exception { + Path database = temporaryFolder.newFolder("rocksdb").toPath(); + + try (Options options = RocksDbSettings.getOptionsByDbName("test")) { + try (RocksDB ignored = RocksDB.open(options, database.toString())) { + // Opening the DB materializes the table factory and persists its native settings. + } + } + + Path optionsFile; + try (Stream files = Files.list(database)) { + optionsFile = files + .filter(path -> path.getFileName().toString().startsWith("OPTIONS-")) + .max(Comparator.comparing(path -> path.getFileName().toString())) + .orElseThrow(() -> new AssertionError("RocksDB OPTIONS file not found")); + } + String nativeOptions = new String(Files.readAllBytes(optionsFile), StandardCharsets.UTF_8); + + assertTrue(nativeOptions.contains("block_size=4096")); + assertTrue(nativeOptions.contains("pin_l0_filter_and_index_blocks_in_cache=false")); + assertTrue(nativeOptions.contains("filter_policy=nullptr")); + } +} diff --git a/common/src/test/java/org/tron/core/config/args/CommitteeConfigTest.java b/common/src/test/java/org/tron/core/config/args/CommitteeConfigTest.java index 559198100fb..f2fe81851ba 100644 --- a/common/src/test/java/org/tron/core/config/args/CommitteeConfigTest.java +++ b/common/src/test/java/org/tron/core/config/args/CommitteeConfigTest.java @@ -1,10 +1,12 @@ package org.tron.core.config.args; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.junit.Test; +import org.tron.core.exception.TronError; public class CommitteeConfigTest { @@ -57,9 +59,16 @@ public void testDynamicEnergyThresholdClamped() { .getDynamicEnergyThreshold()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testAllowOldRewardOptWithoutPrerequisites() { - CommitteeConfig.fromConfig(withRef("committee { allowOldRewardOpt = 1 }")); + TronError error = assertThrows(TronError.class, + () -> CommitteeConfig.fromConfig(withRef("committee { allowOldRewardOpt = 1 }"))); + + assertEquals(TronError.ErrCode.PARAMETER_INIT, error.getErrCode()); + assertEquals("At least one of the following proposals is required to be opened first: " + + "committee.allowNewRewardAlgorithm = 1" + + " or committee.allowNewReward = 1" + + " or committee.allowTvmVote = 1.", error.getMessage()); } @Test diff --git a/consensus/src/main/java/org/tron/consensus/dpos/DposService.java b/consensus/src/main/java/org/tron/consensus/dpos/DposService.java index 397c9d0835c..0a40ec8e076 100644 --- a/consensus/src/main/java/org/tron/consensus/dpos/DposService.java +++ b/consensus/src/main/java/org/tron/consensus/dpos/DposService.java @@ -14,12 +14,12 @@ import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.tron.common.args.GenesisBlock; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Time; import org.tron.consensus.ConsensusDelegate; import org.tron.consensus.base.BlockHandle; import org.tron.consensus.base.ConsensusInterface; @@ -134,14 +134,14 @@ public boolean validBlock(BlockCapsule blockCapsule) { if (slot == 0 && consensusDelegate.getDynamicPropertiesStore().allowConsensusLogicOptimization()) { logger.warn("ValidBlock failed: slot error, witness: {}, timeStamp: {}", - ByteArray.toHexString(witnessAddress.toByteArray()), new DateTime(timeStamp)); + ByteArray.toHexString(witnessAddress.toByteArray()), Time.getIsoTimeString(timeStamp)); return false; } final ByteString scheduledWitness = dposSlot.getScheduledWitness(slot); if (!scheduledWitness.equals(witnessAddress)) { logger.warn("ValidBlock failed: sWitness: {}, bWitness: {}, bTimeStamp: {}, slot: {}", ByteArray.toHexString(scheduledWitness.toByteArray()), - ByteArray.toHexString(witnessAddress.toByteArray()), new DateTime(timeStamp), slot); + ByteArray.toHexString(witnessAddress.toByteArray()), Time.getIsoTimeString(timeStamp), slot); return false; } diff --git a/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java b/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java index 9e42552c80f..38f5614e571 100644 --- a/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java +++ b/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java @@ -6,7 +6,6 @@ import java.util.concurrent.ExecutorService; import lombok.Setter; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; @@ -15,6 +14,7 @@ import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.Time; import org.tron.consensus.ConsensusDelegate; import org.tron.consensus.base.Param.Miner; import org.tron.consensus.base.State; @@ -123,7 +123,7 @@ private State produceBlock() { BlockHeader.raw raw = blockCapsule.getInstance().getBlockHeader().getRawData(); logger.info("Produce block successfully, num: {}, time: {}, witness: {}, ID:{}, parentID:{}", raw.getNumber(), - new DateTime(raw.getTimestamp()), + Time.getIsoTimeString(raw.getTimestamp()), ByteArray.toHexString(raw.getWitnessAddress().toByteArray()), new Sha256Hash(raw.getNumber(), Sha256Hash.of(CommonParameter .getInstance().isECKeyCryptoEngine(), raw.toByteArray())), diff --git a/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java b/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java index 64073210493..d15ea5b2f56 100644 --- a/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java +++ b/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java @@ -76,22 +76,6 @@ public static class Blake2bfDigest implements Digest { v = new long[16]; } - // for tests - Blake2bfDigest( - final long[] h, final long[] m, final long[] t, final boolean f, final long rounds) { - assert rounds <= 4294967295L; // uint max value - buffer = new byte[MESSAGE_LENGTH_BYTES]; - bufferPos = 0; - - this.h = h; - this.m = m; - this.t = t; - this.f = f; - this.rounds = rounds; - - v = new long[16]; - } - @Override public String getAlgorithmName() { return "BLAKE2f"; diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java index 6426ea8a9fe..ecbc681cfb8 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java @@ -37,7 +37,7 @@ * success, 0 as fail

* * Usage:
  • add pairs sequentially with {@link #addPair(BN128G1, BN128G2)}
  • run check - * with {@link #run()} after all paris have been added
  • get result with {@link + * with {@link #run(long)} after all paris have been added
  • get result with {@link * #result()}
* * Arithmetic has been ported from libff @@ -228,7 +228,7 @@ public void addPair(BN128G1 g1, BN128G2 g2) { pairs.add(Pair.of(g1, g2)); } - public void run() { + public boolean run(long vmShouldEndInNs) { for (Pair pair : pairs) { @@ -238,10 +238,16 @@ public void run() { { product = product.mul(miller); } + + if (vmShouldEndInNs < System.nanoTime()) { + return false; + } } // finalize product = finalExponentiation(product); + + return vmShouldEndInNs >= System.nanoTime(); } public int result() { diff --git a/framework/build.gradle b/framework/build.gradle index 8255fc30d18..8edd6714f95 100644 --- a/framework/build.gradle +++ b/framework/build.gradle @@ -11,9 +11,7 @@ apply plugin: 'checkstyle' mainClassName = 'org.tron.program.FullNode' -def versions = [ - checkstyle: '8.7', -] + @@ -40,7 +38,7 @@ dependencies { // end local libraries implementation group: 'com.beust', name: 'jcommander', version: '1.78' implementation group: 'io.dropwizard.metrics', name: 'metrics-core', version: '3.1.2' - implementation('io.netty:netty-codec-protobuf:4.2.15.Final') { + implementation("io.netty:netty-codec-protobuf:${rootProject.nettyVersion}") { exclude group: 'com.google.protobuf' exclude group: 'com.google.protobuf.nano' } @@ -61,17 +59,28 @@ dependencies { testImplementation group: 'org.springframework', name: 'spring-test', version: "${springVersion}" testImplementation group: 'javax.portlet', name: 'portlet-api', version: '3.0.1' + implementation group: 'org.zeromq', name: 'jeromq', version: '0.5.3' api project(":chainbase") api project(":protocol") api project(":actuator") api project(":consensus") + // org.tron.p2p is used directly in 17 files under src/main/java (org.tron.core.net + // and org.tron.core.config.args). It currently arrives only transitively, three + // hops away, because :common exposes it via `api project(":p2p")` -- and :common + // has to, since CommonParameter publishes P2pConfig/PublishConfig in its own API. + // Declare the direct use here as well, so framework keeps compiling if that + // transitive chain is ever narrowed. api, not implementation: framework does + // re-export p2p types -- P2pEventHandlerImpl extends org.tron.p2p.P2pEventHandler, + // HelloMessage.getFrom() returns org.tron.p2p.discover.Node, PeerManager takes + // org.tron.p2p.connection.Channel, Args.loadDnsPublishConfig returns PublishConfig. + api project(":p2p") } check.dependsOn 'lint' checkstyle { - toolVersion = "${versions.checkstyle}" + toolVersion = "${rootProject.checkstyleVersion}" configFile = file("config/checkstyle/checkStyleAll.xml") maxWarnings = 0 } @@ -187,8 +196,14 @@ def binaryRelease(taskName, jarName, mainClass) { } // explicit_dependency + // :p2p is included because :common now exposes it via `api project(":p2p")`, + // so p2p-1.0.0.jar is on runtimeClasspath and gets zipped into the fat jar. + // Without it Gradle reports an implicit_dependency and disables execution + // optimizations, and a parallel build could assemble FullNode.jar before + // :p2p:jar has been written. dependsOn (project(':actuator').jar, project(':consensus').jar, project(':chainbase').jar, - project(':crypto').jar, project(':common').jar, project(':protocol').jar, project(':platform').jar) + project(':crypto').jar, project(':common').jar, project(':protocol').jar, + project(':platform').jar, project(':p2p').jar) from { configurations.runtimeClasspath.collect { diff --git a/framework/src/main/java/org/tron/common/application/ApplicationImpl.java b/framework/src/main/java/org/tron/common/application/ApplicationImpl.java index bab95d299ab..a7c0fd5ca87 100644 --- a/framework/src/main/java/org/tron/common/application/ApplicationImpl.java +++ b/framework/src/main/java/org/tron/common/application/ApplicationImpl.java @@ -10,6 +10,7 @@ import org.tron.core.db.Manager; import org.tron.core.net.TronNetService; import org.tron.core.services.event.EventService; +import org.tron.core.services.jsonrpc.TronJsonRpcImpl; import org.tron.program.SolidityNode; @Slf4j(topic = "app") @@ -37,6 +38,9 @@ public class ApplicationImpl implements Application { @Autowired(required = false) private SolidityNode solidityNode; + @Autowired + private TronJsonRpcImpl tronJsonRpc; + private final CountDownLatch shutdown = new CountDownLatch(1); /** @@ -62,6 +66,9 @@ public void shutdown() { if (solidityNode != null) { solidityNode.close(); } + // Stop the json-rpc filter consumer explicitly, once the producers above are stopped, + // rather than in Spring's destroy phase. + tronJsonRpc.close(); dbManager.close(); shutdown.countDown(); } diff --git a/framework/src/main/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiter.java b/framework/src/main/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiter.java deleted file mode 100644 index cdd71ffee3c..00000000000 --- a/framework/src/main/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiter.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * java-tron is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * java-tron is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with java-tron. If not, see . - */ - -package org.tron.common.application; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import io.grpc.netty.GrpcHttp2ConnectionHandler; -import io.grpc.netty.InternalProtocolNegotiator; -import io.grpc.netty.InternalProtocolNegotiators; -import io.grpc.netty.NettyServerBuilder; -import io.netty.channel.ChannelHandler; -import io.netty.util.AsciiString; - -/** Enforces the advertised HTTP/2 concurrent stream limit for grpc-netty servers. */ -final class GrpcNettyMaxConcurrentStreamsLimiter { - - private GrpcNettyMaxConcurrentStreamsLimiter() { - } - - static NettyServerBuilder configurePlaintext( - NettyServerBuilder builder, int maxConcurrentStreams) { - checkNotNull(builder, "builder"); - checkArgument(maxConcurrentStreams > 0, "maxConcurrentStreams must be positive"); - builder.maxConcurrentCallsPerConnection(maxConcurrentStreams); - // TODO: Remove this shim after https://github.com/grpc/grpc-java/issues/12930 is fixed. - return builder.protocolNegotiator(newPlaintextNegotiator(maxConcurrentStreams)); - } - - static InternalProtocolNegotiator.ProtocolNegotiator newPlaintextNegotiator( - int maxConcurrentStreams) { - checkArgument(maxConcurrentStreams > 0, "maxConcurrentStreams must be positive"); - return new EnforcingProtocolNegotiator( - InternalProtocolNegotiators.serverPlaintext(), maxConcurrentStreams); - } - - private static final class EnforcingProtocolNegotiator - implements InternalProtocolNegotiator.ProtocolNegotiator { - - private final InternalProtocolNegotiator.ProtocolNegotiator delegate; - private final int maxConcurrentStreams; - - private EnforcingProtocolNegotiator( - InternalProtocolNegotiator.ProtocolNegotiator delegate, int maxConcurrentStreams) { - this.delegate = checkNotNull(delegate, "delegate"); - this.maxConcurrentStreams = maxConcurrentStreams; - } - - @Override - public AsciiString scheme() { - return delegate.scheme(); - } - - @Override - public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) { - // grpc-java builds the connection directly, bypassing Netty's builder-side enforcement. - grpcHandler.connection().remote().maxActiveStreams(maxConcurrentStreams); - return delegate.newHandler(grpcHandler); - } - - @Override - public void close() { - delegate.close(); - } - } -} diff --git a/framework/src/main/java/org/tron/common/application/RpcService.java b/framework/src/main/java/org/tron/common/application/RpcService.java index 27fcc479f4e..c398b71ae41 100644 --- a/framework/src/main/java/org/tron/common/application/RpcService.java +++ b/framework/src/main/java/org/tron/common/application/RpcService.java @@ -100,9 +100,8 @@ protected NettyServerBuilder initServerBuilder() { serverBuilder = serverBuilder.executor(this.executorService); } // Set configs from config.conf or default value - serverBuilder = GrpcNettyMaxConcurrentStreamsLimiter.configurePlaintext( - serverBuilder, parameter.getMaxConcurrentCallsPerConnection()); serverBuilder + .maxConcurrentCallsPerConnection(parameter.getMaxConcurrentCallsPerConnection()) .flowControlWindow(parameter.getFlowControlWindow()) .maxConnectionIdle(parameter.getMaxConnectionIdleInMillis(), TimeUnit.MILLISECONDS) .maxConnectionAge(parameter.getMaxConnectionAgeInMillis(), TimeUnit.MILLISECONDS) diff --git a/framework/src/main/java/org/tron/common/logsfilter/queue/FilterCapsuleQueue.java b/framework/src/main/java/org/tron/common/logsfilter/queue/FilterCapsuleQueue.java new file mode 100644 index 00000000000..35f551966f1 --- /dev/null +++ b/framework/src/main/java/org/tron/common/logsfilter/queue/FilterCapsuleQueue.java @@ -0,0 +1,32 @@ +package org.tron.common.logsfilter.queue; + +import com.google.common.annotations.VisibleForTesting; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import org.springframework.stereotype.Component; +import org.tron.common.logsfilter.capsule.FilterTriggerCapsule; + +/** + * Queue between the block-processing producer (Manager) and the json-rpc filter + * consumer (TronJsonRpcImpl), so that neither side references the other. + */ +@Component +public class FilterCapsuleQueue { + + private final BlockingQueue queue = new LinkedBlockingQueue<>(); + + public boolean offer(FilterTriggerCapsule capsule) { + return queue.offer(capsule); + } + + public FilterTriggerCapsule poll(long timeout, TimeUnit unit) throws InterruptedException { + return queue.poll(timeout, unit); + } + + @VisibleForTesting + public Stream stream() { + return queue.stream(); + } +} diff --git a/framework/src/main/java/org/tron/core/Wallet.java b/framework/src/main/java/org/tron/core/Wallet.java index ac54cb2b7ff..7d0b0634c7e 100755 --- a/framework/src/main/java/org/tron/core/Wallet.java +++ b/framework/src/main/java/org/tron/core/Wallet.java @@ -1524,6 +1524,11 @@ public Protocol.ChainParameters getChainParameters() { .setValue(dbManager.getDynamicPropertiesStore().getAllowHardenExchangeCalculation()) .build()); + builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() + .setKey("getAllowOptimizeTvmStorage") + .setValue(dbManager.getDynamicPropertiesStore().getAllowOptimizeTvmStorage()) + .build()); + return builder.build(); } diff --git a/framework/src/main/java/org/tron/core/config/args/Args.java b/framework/src/main/java/org/tron/core/config/args/Args.java index 0bca242606e..a63d3a647d9 100644 --- a/framework/src/main/java/org/tron/core/config/args/Args.java +++ b/framework/src/main/java/org/tron/core/config/args/Args.java @@ -598,7 +598,6 @@ private static void applyNodeConfig(NodeConfig nc) { PARAMETER.trustNodeAddr = nc.getTrustNode(); PARAMETER.validateSignThreadNum = nc.getValidateSignThreadNum(); - PARAMETER.walletExtensionApi = nc.isWalletExtensionApi(); PARAMETER.isOpenFullTcpDisconnect = nc.isOpenFullTcpDisconnect(); PARAMETER.nodeDetectEnable = nc.isNodeDetectEnable(); @@ -1045,8 +1044,9 @@ private static void loadDnsPublishParameters(NodeConfig.DnsConfig dns, String serverType = dns.getServerType(); if (StringUtils.isNotEmpty(serverType)) { if (!"aws".equalsIgnoreCase(serverType) && !"aliyun".equalsIgnoreCase(serverType)) { - throw new IllegalArgumentException( - "Check node.dns.serverType, must be aws or aliyun"); + throw new TronError( + "Check node.dns.serverType, must be aws or aliyun", + TronError.ErrCode.PARAMETER_INIT); } if ("aws".equalsIgnoreCase(serverType)) { publishConfig.setDnsType(DnsType.AwsRoute53); @@ -1088,7 +1088,8 @@ private static void loadDnsPublishParameters(NodeConfig.DnsConfig dns, } private static void logEmptyError(String arg) { - throw new IllegalArgumentException(String.format("Check %s, must not be null or empty", arg)); + throw new TronError(String.format("Check %s, must not be null or empty", arg), + TronError.ErrCode.PARAMETER_INIT); } // createTriggerConfig removed — logic moved to applyEventConfig() @@ -1315,4 +1316,3 @@ private static Map getOptionGroup() { return optionGroupMap; } } - diff --git a/framework/src/main/java/org/tron/core/consensus/ProposalService.java b/framework/src/main/java/org/tron/core/consensus/ProposalService.java index 543deab2fc6..0442078fdec 100644 --- a/framework/src/main/java/org/tron/core/consensus/ProposalService.java +++ b/framework/src/main/java/org/tron/core/consensus/ProposalService.java @@ -412,6 +412,10 @@ public static boolean process(Manager manager, ProposalCapsule proposalCapsule) .saveAllowHardenExchangeCalculation(entry.getValue()); break; } + case ALLOW_OPTIMIZE_TVM_STORAGE: { + manager.getDynamicPropertiesStore().saveAllowOptimizeTvmStorage(entry.getValue()); + break; + } default: find = false; break; diff --git a/framework/src/main/java/org/tron/core/db/HistoryBlockHashUtil.java b/framework/src/main/java/org/tron/core/db/HistoryBlockHashUtil.java index 36f7ee4928d..cfcf573992f 100644 --- a/framework/src/main/java/org/tron/core/db/HistoryBlockHashUtil.java +++ b/framework/src/main/java/org/tron/core/db/HistoryBlockHashUtil.java @@ -150,7 +150,8 @@ public static void write(Manager manager, BlockCapsule block) { return; } long slot = (block.getNum() - 1) % HISTORY_SERVE_WINDOW; - Storage storage = new Storage(HISTORY_STORAGE_ADDRESS, manager.getStorageRowStore()); + Storage storage = new Storage(HISTORY_STORAGE_ADDRESS, manager.getStorageRowStore(), + manager.getDynamicPropertiesStore().allowOptimizeTvmStorage()); storage.put(new DataWord(slot), new DataWord(block.getParentHash().getBytes())); storage.commit(); } diff --git a/framework/src/main/java/org/tron/core/db/Manager.java b/framework/src/main/java/org/tron/core/db/Manager.java index 9d7a7c979b9..d4dbddf2768 100644 --- a/framework/src/main/java/org/tron/core/db/Manager.java +++ b/framework/src/main/java/org/tron/core/db/Manager.java @@ -48,7 +48,6 @@ import org.apache.commons.collections4.CollectionUtils; import org.bouncycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import org.tron.api.GrpcAPI; import org.tron.api.GrpcAPI.TransactionInfoList; @@ -62,11 +61,11 @@ import org.tron.common.logsfilter.capsule.BlockFilterCapsule; import org.tron.common.logsfilter.capsule.BlockLogTriggerCapsule; import org.tron.common.logsfilter.capsule.ContractTriggerCapsule; -import org.tron.common.logsfilter.capsule.FilterTriggerCapsule; import org.tron.common.logsfilter.capsule.LogsFilterCapsule; import org.tron.common.logsfilter.capsule.SolidityTriggerCapsule; import org.tron.common.logsfilter.capsule.TransactionLogTriggerCapsule; import org.tron.common.logsfilter.capsule.TriggerCapsule; +import org.tron.common.logsfilter.queue.FilterCapsuleQueue; import org.tron.common.logsfilter.trigger.ContractEventTrigger; import org.tron.common.logsfilter.trigger.ContractLogTrigger; import org.tron.common.logsfilter.trigger.ContractTrigger; @@ -143,7 +142,6 @@ import org.tron.core.service.MortgageService; import org.tron.core.service.RewardViCalService; import org.tron.core.services.event.exception.EventException; -import org.tron.core.services.jsonrpc.TronJsonRpcImpl; import org.tron.core.store.AccountAssetStore; import org.tron.core.store.AccountIdIndexStore; import org.tron.core.store.AccountIndexStore; @@ -253,8 +251,8 @@ public class Manager { @Getter private BlockingQueue triggerCapsuleQueue; // log filter - private boolean isRunFilterProcessThread = true; - private BlockingQueue filterCapsuleQueue; + @Autowired + private FilterCapsuleQueue filterCapsuleQueue; @Getter private volatile long latestSolidityNumShutDown; @@ -273,16 +271,10 @@ public class Manager { private static final String rePushEsName = "repush"; private ExecutorService triggerEs; private static final String triggerEsName = "event-trigger"; - private ExecutorService filterEs; - private static final String filterEsName = "filter"; @Autowired private RewardViCalService rewardViCalService; - @Lazy - @Autowired - private TronJsonRpcImpl tronJsonRpcImpl; - /** * Cycle thread to rePush Transactions */ @@ -334,26 +326,6 @@ public class Manager { } }; - private Runnable filterProcessLoop = - () -> { - while (isRunFilterProcessThread) { - try { - FilterTriggerCapsule filterCapsule = filterCapsuleQueue.poll(1, TimeUnit.SECONDS); - if (filterCapsule instanceof LogsFilterCapsule) { - tronJsonRpcImpl.handleLogsFilter((LogsFilterCapsule) filterCapsule); - } else if (filterCapsule instanceof BlockFilterCapsule) { - tronJsonRpcImpl.handleBLockFilter((BlockFilterCapsule) filterCapsule); - } - } catch (InterruptedException e) { - logger.error("FilterProcessLoop get InterruptedException, error is {}.", - e.getMessage()); - Thread.currentThread().interrupt(); - } catch (Throwable throwable) { - logger.error("Unknown throwable happened in filterProcessLoop. ", throwable); - } - } - }; - private Comparator downComparator = (Comparator) (o1, o2) -> Long .compare(o2.getOrder(), o1.getOrder()); @@ -476,11 +448,6 @@ public void stopRePushTriggerThread() { ExecutorServiceManager.shutdownAndAwaitTermination(triggerEs, triggerEsName); } - public void stopFilterProcessThread() { - isRunFilterProcessThread = false; - ExecutorServiceManager.shutdownAndAwaitTermination(filterEs, filterEsName); - } - public void stopValidateSignThread() { ExecutorServiceManager.shutdownAndAwaitTermination(validateSignService, "validate-sign"); } @@ -510,7 +477,6 @@ public void init() { this.rePushTransactions = new LinkedBlockingQueue<>(); } this.triggerCapsuleQueue = new LinkedBlockingQueue<>(); - this.filterCapsuleQueue = new LinkedBlockingQueue<>(); chainBaseManager.setMerkleContainer(getMerkleContainer()); chainBaseManager.setMortgageService(mortgageService); this.initGenesis(); @@ -584,12 +550,6 @@ public void init() { ExecutorServiceManager.submit(triggerEs, triggerCapsuleProcessLoop); } - // start json rpc filter process - if (CommonParameter.getInstance().isJsonRpcFilterEnabled()) { - filterEs = ExecutorServiceManager.newSingleThreadExecutor(filterEsName); - ExecutorServiceManager.submit(filterEs, filterProcessLoop); - } - //initStoreFactory prepareStoreFactory(); //initActuatorCreator @@ -2344,9 +2304,7 @@ private void reApplyBlockEvents(List newBranch) { private void postBlockFilter(final BlockCapsule blockCapsule, boolean solidified) { BlockFilterCapsule blockFilterCapsule = new BlockFilterCapsule(blockCapsule, solidified); - if (!filterCapsuleQueue.offer(blockFilterCapsule)) { - logger.info("Too many filters, block filter lost: {}.", blockCapsule.getBlockId()); - } + filterCapsuleQueue.offer(blockFilterCapsule); } private void postLogsFilter(final BlockCapsule blockCapsule, boolean solidified, @@ -2359,9 +2317,7 @@ private void postLogsFilter(final BlockCapsule blockCapsule, boolean solidified, blockCapsule.getBlockId().toString(), blockCapsule.getBloom(), transactionInfoList, solidified, removed); - if (!filterCapsuleQueue.offer(logsFilterCapsule)) { - logger.info("Too many filters, logs filter lost: {}.", blockNumber); - } + filterCapsuleQueue.offer(logsFilterCapsule); } } @@ -2658,7 +2614,6 @@ public void close() { stopRePushThread(); stopRePushTriggerThread(); EventPluginLoader.getInstance().stopPlugin(); - stopFilterProcessThread(); stopValidateSignThread(); chainBaseManager.shutdown(); revokingStore.shutdown(); diff --git a/framework/src/main/java/org/tron/core/metrics/net/NetMetricManager.java b/framework/src/main/java/org/tron/core/metrics/net/NetMetricManager.java index 38dfccff05a..037580037e3 100644 --- a/framework/src/main/java/org/tron/core/metrics/net/NetMetricManager.java +++ b/framework/src/main/java/org/tron/core/metrics/net/NetMetricManager.java @@ -181,7 +181,7 @@ public Protocol.MetricsInfo.NetInfo getNetProtoInfo() { // udp RateInfo udpInTraffic = net.getUdpInTraffic(); Protocol.MetricsInfo.RateInfo udpInTrafficInfo = udpInTraffic.toProtoEntity(); - netInfo.setTcpOutTraffic(udpInTrafficInfo); + netInfo.setUdpInTraffic(udpInTrafficInfo); RateInfo udpOutTraffic = net.getUdpOutTraffic(); Protocol.MetricsInfo.RateInfo udpOutTrafficInfo = udpOutTraffic.toProtoEntity(); netInfo.setUdpOutTraffic(udpOutTrafficInfo); diff --git a/framework/src/main/java/org/tron/core/services/RpcApiService.java b/framework/src/main/java/org/tron/core/services/RpcApiService.java index b9cb05a3b14..9625171acbd 100755 --- a/framework/src/main/java/org/tron/core/services/RpcApiService.java +++ b/framework/src/main/java/org/tron/core/services/RpcApiService.java @@ -63,13 +63,10 @@ import org.tron.api.GrpcAPI.TransactionExtention; import org.tron.api.GrpcAPI.TransactionIdList; import org.tron.api.GrpcAPI.TransactionInfoList; -import org.tron.api.GrpcAPI.TransactionList; -import org.tron.api.GrpcAPI.TransactionListExtention; import org.tron.api.GrpcAPI.TransactionSignWeight; import org.tron.api.GrpcAPI.ViewingKeyMessage; import org.tron.api.GrpcAPI.WitnessList; import org.tron.api.MonitorGrpc; -import org.tron.api.WalletExtensionGrpc; import org.tron.api.WalletGrpc.WalletImplBase; import org.tron.api.WalletSolidityGrpc.WalletSolidityImplBase; import org.tron.common.application.RpcService; @@ -181,6 +178,8 @@ public class RpcApiService extends RpcService { private MetricsApiService metricsApiService; @Getter private DatabaseApi databaseApi = new DatabaseApi(); + // WalletApi is the full protocol.Wallet impl (HEAD); WalletSolidityApi is its read-only subset, + // reused by the Solidity/PBFT cursor ports. private WalletApi walletApi = new WalletApi(); @Getter private WalletSolidityApi walletSolidityApi = new WalletSolidityApi(); @@ -199,9 +198,6 @@ protected void addService(NettyServerBuilder serverBuilder) { CommonParameter parameter = Args.getInstance(); if (parameter.isSolidityNode()) { serverBuilder.addService(walletSolidityApi); - if (parameter.isWalletExtensionApi()) { - serverBuilder.addService(new WalletExtensionApi()); - } } else { serverBuilder.addService(walletApi); } @@ -362,249 +358,138 @@ public void getDynamicProperties(EmptyMessage request, } /** - * WalletSolidityApi. + * WalletSolidityApi is the full implementation of the {@code protocol.WalletSolidity} gRPC + * service. Every method here is read-only and also present on {@link WalletApi}, so each one + * delegates to the shared {@code WalletApi} singleton instead of repeating its body. */ public class WalletSolidityApi extends WalletSolidityImplBase { @Override public void getAccount(Account request, StreamObserver responseObserver) { - ByteString addressBs = request.getAddress(); - if (addressBs != null) { - Account reply = wallet.getAccount(request); - responseObserver.onNext(reply); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getAccount(request, responseObserver); } @Override public void getAccountById(Account request, StreamObserver responseObserver) { - ByteString id = request.getAccountId(); - if (id != null) { - Account reply = wallet.getAccountById(request); - responseObserver.onNext(reply); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getAccountById(request, responseObserver); } @Override public void listWitnesses(EmptyMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getWitnessList()); - responseObserver.onCompleted(); + walletApi.listWitnesses(request, responseObserver); } @Override public void getPaginatedNowWitnessList(PaginatedMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext( - wallet.getPaginatedNowWitnessList(request.getOffset(), request.getLimit())); - } catch (MaintenanceUnavailableException e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getPaginatedNowWitnessList(request, responseObserver); } @Override public void getAssetIssueList(EmptyMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getAssetIssueList()); - responseObserver.onCompleted(); + walletApi.getAssetIssueList(request, responseObserver); } @Override public void getPaginatedAssetIssueList(PaginatedMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getAssetIssueList(request.getOffset(), request.getLimit())); - responseObserver.onCompleted(); + walletApi.getPaginatedAssetIssueList(request, responseObserver); } @Override public void getAssetIssueByName(BytesMessage request, StreamObserver responseObserver) { - ByteString assetName = request.getValue(); - if (assetName != null) { - try { - responseObserver.onNext(wallet.getAssetIssueByName(assetName)); - } catch (NonUniqueObjectException e) { - responseObserver.onNext(null); - logger.debug("Solidity NonUniqueObjectException: {}", e.getMessage()); - } - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getAssetIssueByName(request, responseObserver); } @Override public void getAssetIssueListByName(BytesMessage request, StreamObserver responseObserver) { - ByteString assetName = request.getValue(); - - if (assetName != null) { - responseObserver.onNext(wallet.getAssetIssueListByName(assetName)); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getAssetIssueListByName(request, responseObserver); } @Override public void getAssetIssueById(BytesMessage request, StreamObserver responseObserver) { - ByteString assetId = request.getValue(); - - if (assetId != null) { - responseObserver.onNext(wallet.getAssetIssueById(assetId.toStringUtf8())); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getAssetIssueById(request, responseObserver); } @Override public void getNowBlock(EmptyMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getNowBlock()); - responseObserver.onCompleted(); + walletApi.getNowBlock(request, responseObserver); } @Override public void getNowBlock2(EmptyMessage request, StreamObserver responseObserver) { - responseObserver.onNext(block2Extention(wallet.getNowBlock())); - responseObserver.onCompleted(); + walletApi.getNowBlock2(request, responseObserver); } @Override public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - long num = request.getNum(); - if (num >= 0) { - Block reply = wallet.getBlockByNum(num); - responseObserver.onNext(reply); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getBlockByNum(request, responseObserver); } @Override public void getBlockByNum2(NumberMessage request, StreamObserver responseObserver) { - long num = request.getNum(); - if (num >= 0) { - Block reply = wallet.getBlockByNum(num); - responseObserver.onNext(block2Extention(reply)); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getBlockByNum2(request, responseObserver); } @Override public void getDelegatedResource(DelegatedResourceMessage request, StreamObserver responseObserver) { - responseObserver - .onNext(wallet.getDelegatedResource(request.getFromAddress(), request.getToAddress())); - responseObserver.onCompleted(); + walletApi.getDelegatedResource(request, responseObserver); } @Override public void getDelegatedResourceV2(DelegatedResourceMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getDelegatedResourceV2( - request.getFromAddress(), request.getToAddress()) - ); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getDelegatedResourceV2(request, responseObserver); } @Override public void getDelegatedResourceAccountIndex(BytesMessage request, StreamObserver responseObserver) { - try { - responseObserver - .onNext(wallet.getDelegatedResourceAccountIndex(request.getValue())); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getDelegatedResourceAccountIndex(request, responseObserver); } @Override public void getDelegatedResourceAccountIndexV2(BytesMessage request, StreamObserver responseObserver) { - try { - responseObserver - .onNext(wallet.getDelegatedResourceAccountIndexV2(request.getValue())); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getDelegatedResourceAccountIndexV2(request, responseObserver); } @Override public void getCanDelegatedMaxSize(GrpcAPI.CanDelegatedMaxSizeRequestMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getCanDelegatedMaxSize( - request.getOwnerAddress(),request.getType())); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getCanDelegatedMaxSize(request, responseObserver); } @Override public void getAvailableUnfreezeCount(GrpcAPI.GetAvailableUnfreezeCountRequestMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getAvailableUnfreezeCount( - request.getOwnerAddress())); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getAvailableUnfreezeCount(request, responseObserver); } @Override public void getCanWithdrawUnfreezeAmount(CanWithdrawUnfreezeAmountRequestMessage request, StreamObserver responseObserver) { - try { - responseObserver - .onNext(wallet.getCanWithdrawUnfreezeAmount( - request.getOwnerAddress(), request.getTimestamp()) - ); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getCanWithdrawUnfreezeAmount(request, responseObserver); } @Override public void getExchangeById(BytesMessage request, StreamObserver responseObserver) { - ByteString exchangeId = request.getValue(); - - if (Objects.nonNull(exchangeId)) { - responseObserver.onNext(wallet.getExchangeById(exchangeId)); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getExchangeById(request, responseObserver); } @Override public void listExchanges(EmptyMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getExchangeList()); - responseObserver.onCompleted(); + walletApi.listExchanges(request, responseObserver); } @Override @@ -616,29 +501,13 @@ public void getTransactionCountByBlockNum(NumberMessage request, @Override public void getTransactionById(BytesMessage request, StreamObserver responseObserver) { - ByteString id = request.getValue(); - if (null != id) { - Transaction reply = wallet.getTransactionById(id); - - responseObserver.onNext(reply); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getTransactionById(request, responseObserver); } @Override public void getTransactionInfoById(BytesMessage request, StreamObserver responseObserver) { - ByteString id = request.getValue(); - if (null != id) { - TransactionInfo reply = wallet.getTransactionInfoById(id); - - responseObserver.onNext(reply); - } else { - responseObserver.onNext(null); - } - responseObserver.onCompleted(); + walletApi.getTransactionInfoById(request, responseObserver); } @Override @@ -661,198 +530,78 @@ public void getBurnTrx(EmptyMessage request, StreamObserver respo @Override public void getMerkleTreeVoucherInfo(OutputPointInfo request, StreamObserver responseObserver) { - - try { - IncrementalMerkleVoucherInfo witnessInfo = wallet - .getMerkleTreeVoucherInfo(request); - responseObserver.onNext(witnessInfo); - } catch (Exception ex) { - responseObserver.onError(getRunTimeException(ex)); - } - responseObserver.onCompleted(); + walletApi.getMerkleTreeVoucherInfo(request, responseObserver); } @Override public void scanNoteByIvk(GrpcAPI.IvkDecryptParameters request, StreamObserver responseObserver) { - long startNum = request.getStartBlockIndex(); - long endNum = request.getEndBlockIndex(); - - try { - DecryptNotes decryptNotes = wallet - .scanNoteByIvk(startNum, endNum, request.getIvk().toByteArray()); - responseObserver.onNext(decryptNotes); - } catch (BadItemException | ZksnarkException e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.scanNoteByIvk(request, responseObserver); } @Override public void scanAndMarkNoteByIvk(GrpcAPI.IvkDecryptAndMarkParameters request, StreamObserver responseObserver) { - long startNum = request.getStartBlockIndex(); - long endNum = request.getEndBlockIndex(); - - try { - DecryptNotesMarked decryptNotes = wallet.scanAndMarkNoteByIvk(startNum, endNum, - request.getIvk().toByteArray(), - request.getAk().toByteArray(), - request.getNk().toByteArray()); - responseObserver.onNext(decryptNotes); - } catch (BadItemException | ZksnarkException | InvalidProtocolBufferException - | ItemNotFoundException e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.scanAndMarkNoteByIvk(request, responseObserver); } @Override public void scanNoteByOvk(GrpcAPI.OvkDecryptParameters request, StreamObserver responseObserver) { - long startNum = request.getStartBlockIndex(); - long endNum = request.getEndBlockIndex(); - try { - DecryptNotes decryptNotes = wallet - .scanNoteByOvk(startNum, endNum, request.getOvk().toByteArray()); - responseObserver.onNext(decryptNotes); - } catch (BadItemException | ZksnarkException e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.scanNoteByOvk(request, responseObserver); } @Override public void isSpend(NoteParameters request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.isSpend(request)); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.isSpend(request, responseObserver); } @Override public void scanShieldedTRC20NotesByIvk(IvkDecryptTRC20Parameters request, StreamObserver responseObserver) { - if (rejectIfEventsPresent(responseObserver, request.getEventsList())) { - return; - } - long startNum = request.getStartBlockIndex(); - long endNum = request.getEndBlockIndex(); - byte[] contractAddress = request.getShieldedTRC20ContractAddress().toByteArray(); - byte[] ivk = request.getIvk().toByteArray(); - byte[] ak = request.getAk().toByteArray(); - byte[] nk = request.getNk().toByteArray(); - - try { - responseObserver.onNext( - wallet.scanShieldedTRC20NotesByIvk(startNum, endNum, contractAddress, ivk, ak, nk)); - - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.scanShieldedTRC20NotesByIvk(request, responseObserver); } @Override public void scanShieldedTRC20NotesByOvk(OvkDecryptTRC20Parameters request, StreamObserver responseObserver) { - if (rejectIfEventsPresent(responseObserver, request.getEventsList())) { - return; - } - long startNum = request.getStartBlockIndex(); - long endNum = request.getEndBlockIndex(); - byte[] contractAddress = request.getShieldedTRC20ContractAddress().toByteArray(); - byte[] ovk = request.getOvk().toByteArray(); - try { - responseObserver - .onNext(wallet.scanShieldedTRC20NotesByOvk(startNum, endNum, ovk, contractAddress)); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.scanShieldedTRC20NotesByOvk(request, responseObserver); } @Override public void isShieldedTRC20ContractNoteSpent(NfTRC20Parameters request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.isShieldedTRC20ContractNoteSpent(request)); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.isShieldedTRC20ContractNoteSpent(request, responseObserver); } @Override public void getMarketOrderByAccount(BytesMessage request, StreamObserver responseObserver) { - try { - ByteString address = request.getValue(); - - MarketOrderList marketOrderList = wallet - .getMarketOrderByAccount(address); - responseObserver.onNext(marketOrderList); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getMarketOrderByAccount(request, responseObserver); } @Override public void getMarketOrderById(BytesMessage request, StreamObserver responseObserver) { - try { - ByteString address = request.getValue(); - - MarketOrder marketOrder = wallet - .getMarketOrderById(address); - responseObserver.onNext(marketOrder); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getMarketOrderById(request, responseObserver); } @Override public void getMarketPriceByPair(MarketOrderPair request, StreamObserver responseObserver) { - try { - MarketPriceList marketPriceList = wallet - .getMarketPriceByPair(request.getSellTokenId().toByteArray(), - request.getBuyTokenId().toByteArray()); - responseObserver.onNext(marketPriceList); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getMarketPriceByPair(request, responseObserver); } @Override public void getMarketOrderListByPair(org.tron.protos.Protocol.MarketOrderPair request, StreamObserver responseObserver) { - try { - MarketOrderList orderPairList = wallet - .getMarketOrderListByPair(request.getSellTokenId().toByteArray(), - request.getBuyTokenId().toByteArray()); - responseObserver.onNext(orderPairList); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getMarketOrderListByPair(request, responseObserver); } @Override public void getMarketPairList(EmptyMessage request, StreamObserver responseObserver) { - try { - MarketOrderPairList pairList = wallet.getMarketPairList(); - responseObserver.onNext(pairList); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getMarketPairList(request, responseObserver); } @Override @@ -865,45 +614,13 @@ public void triggerConstantContract(TriggerSmartContract request, @Override public void estimateEnergy(TriggerSmartContract request, StreamObserver responseObserver) { - TransactionExtention.Builder trxExtBuilder = TransactionExtention.newBuilder(); - Return.Builder retBuilder = Return.newBuilder(); - EstimateEnergyMessage.Builder estimateBuilder - = EstimateEnergyMessage.newBuilder(); - - try { - TransactionCapsule trxCap = createTransactionCapsule(request, - ContractType.TriggerSmartContract); - wallet.estimateEnergy(request, trxCap, trxExtBuilder, retBuilder, estimateBuilder); - } catch (ContractValidateException | VMIllegalException e) { - retBuilder.setResult(false).setCode(response_code.CONTRACT_VALIDATE_ERROR) - .setMessage(ByteString.copyFromUtf8(Wallet - .CONTRACT_VALIDATE_ERROR + e.getMessage())); - logger.warn(CONTRACT_VALIDATE_EXCEPTION, e.getMessage()); - } catch (RuntimeException e) { - retBuilder.setResult(false).setCode(response_code.CONTRACT_EXE_ERROR) - .setMessage(ByteString.copyFromUtf8(e.getClass() + " : " + e.getMessage())); - logger.warn("When run estimate energy in VM, have Runtime Exception: " + e.getMessage()); - } catch (Exception e) { - retBuilder.setResult(false).setCode(response_code.OTHER_ERROR) - .setMessage(ByteString.copyFromUtf8(e.getClass() + " : " + e.getMessage())); - logger.warn(UNKNOWN_EXCEPTION_CAUGHT + e.getMessage(), e); - } finally { - estimateBuilder.setResult(retBuilder); - responseObserver.onNext(estimateBuilder.build()); - responseObserver.onCompleted(); - } + walletApi.estimateEnergy(request, responseObserver); } @Override public void getTransactionInfoByBlockNum(NumberMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getTransactionInfoByBlockNum(request.getNum())); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - - responseObserver.onCompleted(); + walletApi.getTransactionInfoByBlockNum(request, responseObserver); } @Override @@ -915,40 +632,13 @@ public void getBlock(GrpcAPI.BlockReq request, @Override public void getBandwidthPrices(EmptyMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getBandwidthPrices()); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); + walletApi.getBandwidthPrices(request, responseObserver); } @Override public void getEnergyPrices(EmptyMessage request, StreamObserver responseObserver) { - try { - responseObserver.onNext(wallet.getEnergyPrices()); - } catch (Exception e) { - responseObserver.onError(getRunTimeException(e)); - } - responseObserver.onCompleted(); - } - } - - /** - * WalletExtensionApi. - */ - public class WalletExtensionApi extends WalletExtensionGrpc.WalletExtensionImplBase { - - private TransactionListExtention transactionList2Extention(TransactionList transactionList) { - if (transactionList == null) { - return null; - } - TransactionListExtention.Builder builder = TransactionListExtention.newBuilder(); - for (Transaction transaction : transactionList.getTransactionList()) { - builder.addTransaction(transaction2Extention(transaction)); - } - return builder.build(); + walletApi.getEnergyPrices(request, responseObserver); } } @@ -1479,15 +1169,26 @@ public void getNowBlock2(EmptyMessage request, @Override public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - responseObserver.onNext(wallet.getBlockByNum(request.getNum())); + long num = request.getNum(); + if (num >= 0) { + Block reply = wallet.getBlockByNum(num); + responseObserver.onNext(reply); + } else { + responseObserver.onNext(null); + } responseObserver.onCompleted(); } @Override public void getBlockByNum2(NumberMessage request, StreamObserver responseObserver) { - Block block = wallet.getBlockByNum(request.getNum()); - responseObserver.onNext(block2Extention(block)); + long num = request.getNum(); + if (num >= 0) { + Block reply = wallet.getBlockByNum(num); + responseObserver.onNext(block2Extention(reply)); + } else { + responseObserver.onNext(null); + } responseObserver.onCompleted(); } @@ -1594,7 +1295,7 @@ public void getAssetIssueByName(BytesMessage request, responseObserver.onNext(wallet.getAssetIssueByName(assetName)); } catch (NonUniqueObjectException e) { responseObserver.onNext(null); - logger.debug("FullNode NonUniqueObjectException: {}", e.getMessage()); + logger.debug("NonUniqueObjectException: {}", e.getMessage()); } } else { responseObserver.onNext(null); @@ -1881,6 +1582,7 @@ public void getPaginatedNowWitnessList(PaginatedMessage request, wallet.getPaginatedNowWitnessList(request.getOffset(), request.getLimit())); } catch (MaintenanceUnavailableException e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1910,6 +1612,7 @@ public void getDelegatedResourceV2(DelegatedResourceMessage request, ); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1922,6 +1625,7 @@ public void getDelegatedResourceAccountIndex(BytesMessage request, .onNext(wallet.getDelegatedResourceAccountIndex(request.getValue())); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1934,6 +1638,7 @@ public void getDelegatedResourceAccountIndexV2(BytesMessage request, .onNext(wallet.getDelegatedResourceAccountIndexV2(request.getValue())); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1946,6 +1651,7 @@ public void getCanDelegatedMaxSize(GrpcAPI.CanDelegatedMaxSizeRequestMessage req request.getOwnerAddress(), request.getType())); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); @@ -1959,6 +1665,7 @@ public void getAvailableUnfreezeCount(GrpcAPI.GetAvailableUnfreezeCountRequestMe request.getOwnerAddress())); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); @@ -1974,6 +1681,7 @@ public void getCanWithdrawUnfreezeAmount(CanWithdrawUnfreezeAmountRequestMessage )); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1985,6 +1693,7 @@ public void getBandwidthPrices(EmptyMessage request, responseObserver.onNext(wallet.getBandwidthPrices()); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -1996,6 +1705,7 @@ public void getEnergyPrices(EmptyMessage request, responseObserver.onNext(wallet.getEnergyPrices()); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2007,6 +1717,7 @@ public void getMemoFee(EmptyMessage request, responseObserver.onNext(wallet.getMemoFeePrices()); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2063,6 +1774,7 @@ public void getNodeInfo(EmptyMessage request, StreamObserver responseO responseObserver.onNext(nodeInfoService.getNodeInfo().transferToProtoEntity()); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2539,6 +2251,7 @@ public void getTransactionInfoByBlockNum(NumberMessage request, responseObserver.onNext(wallet.getTransactionInfoByBlockNum(request.getNum())); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); @@ -2568,6 +2281,7 @@ public void getMarketOrderByAccount(BytesMessage request, responseObserver.onNext(marketOrderList); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2583,6 +2297,7 @@ public void getMarketOrderById(BytesMessage request, responseObserver.onNext(marketOrder); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2597,6 +2312,7 @@ public void getMarketPriceByPair(MarketOrderPair request, responseObserver.onNext(marketPriceList); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2611,6 +2327,7 @@ public void getMarketOrderListByPair(org.tron.protos.Protocol.MarketOrderPair re responseObserver.onNext(orderPairList); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2623,6 +2340,7 @@ public void getMarketPairList(EmptyMessage request, responseObserver.onNext(pairList); } catch (Exception e) { responseObserver.onError(getRunTimeException(e)); + return; } responseObserver.onCompleted(); } @@ -2672,6 +2390,7 @@ public void getRewardInfoCommon(BytesMessage request, responseObserver.onNext(builder.build()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2685,6 +2404,7 @@ public void getBurnTrxCommon(EmptyMessage request, responseObserver.onNext(builder.build()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2700,6 +2420,7 @@ public void getBrokerageInfoCommon(BytesMessage request, responseObserver.onNext(builder.build()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2726,6 +2447,7 @@ public void getTransactionFromPendingCommon(BytesMessage request, responseObserver.onNext(transactionCapsule == null ? null : transactionCapsule.getInstance()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2738,6 +2460,7 @@ public void getTransactionListFromPendingCommon(EmptyMessage request, responseObserver.onNext(builder.build()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2750,6 +2473,7 @@ public void getPendingSizeCommon(EmptyMessage request, responseObserver.onNext(builder.build()); } catch (Exception e) { responseObserver.onError(e); + return; } responseObserver.onCompleted(); } @@ -2765,6 +2489,7 @@ public void getBlockCommon(GrpcAPI.BlockReq request, } else { responseObserver.onError(getRunTimeException(e)); } + return; } responseObserver.onCompleted(); } diff --git a/framework/src/main/java/org/tron/core/services/filter/CharResponseWrapper.java b/framework/src/main/java/org/tron/core/services/filter/CharResponseWrapper.java deleted file mode 100644 index e6421c6a257..00000000000 --- a/framework/src/main/java/org/tron/core/services/filter/CharResponseWrapper.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.tron.core.services.filter; - -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; - -public class CharResponseWrapper extends HttpServletResponseWrapper { - - private ServletOutputStream outputStream; - private PrintWriter writer; - private ServletOutputStreamCopy streamCopy; - - - public CharResponseWrapper(HttpServletResponse response) throws IOException { - super(response); - } - - @Override - public ServletOutputStream getOutputStream() throws IOException { - if (writer != null) { - throw new IllegalStateException("getWriter() has been called ."); - } - - if (outputStream == null) { - outputStream = getResponse().getOutputStream(); - streamCopy = new ServletOutputStreamCopy(outputStream); - } - - return streamCopy; - } - - @Override - public PrintWriter getWriter() throws IOException { - if (outputStream != null) { - throw new IllegalStateException("getOutputStream() has been called."); - } - - if (writer == null) { - streamCopy = new ServletOutputStreamCopy(getResponse().getOutputStream()); - // set auto flash so that copy can be valid - writer = new PrintWriter(new OutputStreamWriter(streamCopy, - getResponse().getCharacterEncoding()), true); - } - - return writer; - } - - @Override - public void flushBuffer() throws IOException { // flush both stream - if (writer != null) { - writer.flush(); - } else if (outputStream != null) { - streamCopy.flush(); - } - } - - public int getByteSize() { - return streamCopy == null ? 0 : streamCopy.getStreamByteSize(); - } - -} \ No newline at end of file diff --git a/framework/src/main/java/org/tron/core/services/filter/CursorServerInterceptor.java b/framework/src/main/java/org/tron/core/services/filter/CursorServerInterceptor.java new file mode 100644 index 00000000000..74d14daede9 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/filter/CursorServerInterceptor.java @@ -0,0 +1,52 @@ +package org.tron.core.services.filter; + +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.tron.core.db.Manager; +import org.tron.core.db2.core.Chainbase; + +/** + * Switches the current thread's read cursor around the synchronous handler callback and restores it + * afterwards, so the handler reads from the snapshot its subclass selects (HEAD / SOLIDITY / PBFT); + * the services behind it never touch the cursor. + * + *

Two invariants it relies on: + *

    + *
  • The bracket wraps {@code onHalfClose()} — where gRPC runs the unary handler inline — not + * {@code interceptCall}, which may land on another pool thread; the cursor is a + * {@link ThreadLocal}, so setting it elsewhere fails silently and the port serves HEAD. + *
  • Handlers must be synchronous: the cursor is reset when {@code onHalfClose} returns, so a read + * deferred to another thread would read HEAD. + *
+ * + *

The {@code finally} reset is mandatory: the fixed thread pool is reused, so a leftover cursor + * leaks into the next call on that thread. + */ +public abstract class CursorServerInterceptor implements ServerInterceptor { + + @Autowired + protected Manager dbManager; + + /** Snapshot every call on this server reads from; set by the subclass. */ + protected Chainbase.Cursor cursor; + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + return new SimpleForwardingServerCallListener(next.startCall(call, headers)) { + @Override + public void onHalfClose() { + try { + dbManager.setCursor(cursor); + super.onHalfClose(); + } finally { + dbManager.resetCursor(); + } + } + }; + } +} diff --git a/framework/src/main/java/org/tron/core/services/filter/HttpApiAccessFilter.java b/framework/src/main/java/org/tron/core/services/filter/HttpApiAccessFilter.java index e18e6541baa..14149934f0b 100644 --- a/framework/src/main/java/org/tron/core/services/filter/HttpApiAccessFilter.java +++ b/framework/src/main/java/org/tron/core/services/filter/HttpApiAccessFilter.java @@ -29,9 +29,9 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha if (request instanceof HttpServletRequest) { String contextPath = ((HttpServletRequest) request).getContextPath(); String endpoint = contextPath + ((HttpServletRequest) request).getServletPath(); - HttpServletResponse resp = (HttpServletResponse) response; if (isDisabled(endpoint)) { + HttpServletResponse resp = (HttpServletResponse) response; resp.setStatus(HttpServletResponse.SC_NOT_FOUND); resp.setContentType("application/json; charset=utf-8"); JSONObject jsonObject = new JSONObject(); @@ -39,14 +39,10 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha resp.getWriter().println(jsonObject.toJSONString()); return; } - - CharResponseWrapper responseWrapper = new CharResponseWrapper(resp); - chain.doFilter(request, responseWrapper); - - } else { - chain.doFilter(request, response); } + chain.doFilter(request, response); + } catch (Exception e) { logger.error("http api access filter exception: {}", e.getMessage()); } @@ -74,6 +70,3 @@ private boolean isDisabled(String endpoint) { } } - - - diff --git a/framework/src/main/java/org/tron/core/services/filter/HttpInterceptor.java b/framework/src/main/java/org/tron/core/services/filter/HttpInterceptor.java index ed20630b780..0367fe25580 100644 --- a/framework/src/main/java/org/tron/core/services/filter/HttpInterceptor.java +++ b/framework/src/main/java/org/tron/core/services/filter/HttpInterceptor.java @@ -10,6 +10,7 @@ import lombok.extern.slf4j.Slf4j; import org.eclipse.jetty.http.BadMessageException; import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.server.Request; import org.tron.common.prometheus.MetricKeys; import org.tron.common.prometheus.MetricLabels; import org.tron.common.prometheus.Metrics; @@ -37,17 +38,15 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha } String contextPath = ((HttpServletRequest) request).getContextPath(); endpoint = contextPath + ((HttpServletRequest) request).getServletPath(); - CharResponseWrapper responseWrapper = new CharResponseWrapper( - (HttpServletResponse) response); - chain.doFilter(request, responseWrapper); + chain.doFilter(request, response); HttpServletResponse resp = (HttpServletResponse) response; - int size = responseWrapper.getByteSize(); + long size = getContentCount(request); MetricsUtil.meterMark(MetricsKey.NET_API_OUT_TRAFFIC, size); MetricsUtil.meterMark(MetricsKey.NET_API_QPS); if (resp.getStatus() >= HTTP_BAD_REQUEST && resp.getStatus() <= HTTP_NOT_ACCEPTABLE) { MetricsUtil.meterMark(MetricsKey.NET_API_FAIL_QPS); Metrics.histogramObserve(MetricKeys.Histogram.HTTP_BYTES, - size, MetricLabels.UNDEFINED, String.valueOf(responseWrapper.getStatus())); + size, MetricLabels.UNDEFINED, String.valueOf(resp.getStatus())); return; } if (resp.getStatus() == HTTP_SUCCESS) { @@ -58,7 +57,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha } MetricsUtil.meterMark(MetricsKey.NET_API_DETAIL_OUT_TRAFFIC + endpoint, size); Metrics.histogramObserve(MetricKeys.Histogram.HTTP_BYTES, - size, endpoint, String.valueOf(responseWrapper.getStatus())); + size, endpoint, String.valueOf(resp.getStatus())); } catch (Exception e) { String key = MetricsKey.NET_API_DETAIL_QPS + endpoint; if (MetricsUtil.getMeters(MetricsKey.NET_API_DETAIL_QPS).containsKey(key)) { @@ -74,9 +73,12 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha } } + private long getContentCount(ServletRequest request) { + Request baseRequest = Request.getBaseRequest(request); + return baseRequest == null ? 0L : baseRequest.getResponse().getContentCount(); + } + @Override public void destroy() { } } - - diff --git a/framework/src/main/java/org/tron/core/services/filter/PbftCursorInterceptor.java b/framework/src/main/java/org/tron/core/services/filter/PbftCursorInterceptor.java new file mode 100644 index 00000000000..3ea55501d35 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/filter/PbftCursorInterceptor.java @@ -0,0 +1,15 @@ +package org.tron.core.services.filter; + +import org.springframework.stereotype.Component; +import org.tron.core.db2.core.Chainbase; + +/** + * Makes every call on the PBFT gRPC server read the PBFT-confirmed state view. + */ +@Component +public class PbftCursorInterceptor extends CursorServerInterceptor { + + public PbftCursorInterceptor() { + this.cursor = Chainbase.Cursor.PBFT; + } +} diff --git a/framework/src/main/java/org/tron/core/services/filter/ServletOutputStreamCopy.java b/framework/src/main/java/org/tron/core/services/filter/ServletOutputStreamCopy.java deleted file mode 100644 index d29b4a4fa57..00000000000 --- a/framework/src/main/java/org/tron/core/services/filter/ServletOutputStreamCopy.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.tron.core.services.filter; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import javax.servlet.ServletOutputStream; -import javax.servlet.WriteListener; - -class ServletOutputStreamCopy extends ServletOutputStream { - - private OutputStream outputStream; - private ByteArrayOutputStream copy; - private int MAX_RESPONSE_SIZE = 4096; - - public ServletOutputStreamCopy(OutputStream outputStream) { - this.outputStream = outputStream; - this.copy = new ByteArrayOutputStream(MAX_RESPONSE_SIZE); - } - - @Override - public void write(int b) throws IOException { - outputStream.write(b); - copy.write(b); - } - - public int getStreamByteSize() { - return this.copy.size(); - } - - @Override - public boolean isReady() { - return false; - } - - @Override - public void setWriteListener(WriteListener writeListener) { - - } -} diff --git a/framework/src/main/java/org/tron/core/services/filter/SolidityCursorInterceptor.java b/framework/src/main/java/org/tron/core/services/filter/SolidityCursorInterceptor.java new file mode 100644 index 00000000000..5cf95ca0db4 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/filter/SolidityCursorInterceptor.java @@ -0,0 +1,15 @@ +package org.tron.core.services.filter; + +import org.springframework.stereotype.Component; +import org.tron.core.db2.core.Chainbase; + +/** + * Makes every call on the Solidity gRPC server read the solidified state view. + */ +@Component +public class SolidityCursorInterceptor extends CursorServerInterceptor { + + public SolidityCursorInterceptor() { + this.cursor = Chainbase.Cursor.SOLIDITY; + } +} diff --git a/framework/src/main/java/org/tron/core/services/http/BroadcastServlet.java b/framework/src/main/java/org/tron/core/services/http/BroadcastServlet.java index 370a81eef4e..844d606ebb2 100644 --- a/framework/src/main/java/org/tron/core/services/http/BroadcastServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/BroadcastServlet.java @@ -28,7 +28,8 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) String transactionID = ByteArray .toHexString(transactionCapsule.getTransactionId().getBytes()); GrpcAPI.Return result = wallet.broadcastTransaction(transaction); - JSONObject res = JSONObject.parseObject(JsonFormat.printToString(result, params.isVisible())); + JSONObject res = JSONObject.outboundParseObject( + JsonFormat.printToString(result, params.isVisible())); res.put("txid", transactionID); response.getWriter().println(res.toJSONString()); } catch (Exception e) { diff --git a/framework/src/main/java/org/tron/core/services/http/CreateShieldedTransactionWithoutSpendAuthSigServlet.java b/framework/src/main/java/org/tron/core/services/http/CreateShieldedTransactionWithoutSpendAuthSigServlet.java index eb870bd1721..8b46d4544f5 100644 --- a/framework/src/main/java/org/tron/core/services/http/CreateShieldedTransactionWithoutSpendAuthSigServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/CreateShieldedTransactionWithoutSpendAuthSigServlet.java @@ -7,7 +7,6 @@ import org.springframework.stereotype.Component; import org.tron.api.GrpcAPI.PrivateParametersWithoutAsk; import org.tron.core.Wallet; -import org.tron.json.JSON; import org.tron.json.JSONObject; import org.tron.protos.Protocol.Transaction; @@ -32,7 +31,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) .createShieldedTransactionWithoutSpendAuthSig(build.build()) .getInstance(); String txString = Util.printCreateTransaction(tx, params.isVisible()); - JSONObject jsonObject = JSON.parseObject(txString); + JSONObject jsonObject = JSONObject.outboundParseObject(txString); if (jsonObject.containsKey("txID")) { jsonObject.remove("txID"); } diff --git a/framework/src/main/java/org/tron/core/services/http/GetBlockServlet.java b/framework/src/main/java/org/tron/core/services/http/GetBlockServlet.java index 2320fc87c7d..a953ae11802 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetBlockServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetBlockServlet.java @@ -77,9 +77,7 @@ private void fillResponse(boolean visible, BlockReq request, HttpServletResponse response.getWriter().println("{}"); } } catch (IllegalArgumentException e) { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("Error", e.getMessage()); - response.getWriter().println(jsonObject.toJSONString()); + Util.writeAuditedError(e.getMessage(), response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetBrokerageServlet.java b/framework/src/main/java/org/tron/core/services/http/GetBrokerageServlet.java index 1fbd94fe690..b735878d1e1 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetBrokerageServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetBrokerageServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -27,12 +26,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { } response.getWriter().println("{\"brokerage\": " + value + "}"); } catch (DecoderException | IllegalArgumentException e) { - try { - response.getWriter() - .println("{\"Error\": " + "\"INVALID address, " + e.getMessage() + "\"}"); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.writeAuditedError(Util.INVALID_ADDRESS_MSG, response); } catch (Exception e) { Util.processError(e, response); } diff --git a/framework/src/main/java/org/tron/core/services/http/GetBurnTrxServlet.java b/framework/src/main/java/org/tron/core/services/http/GetBurnTrxServlet.java index ea066a6e98c..3a19825ba75 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetBurnTrxServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetBurnTrxServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -24,12 +23,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { : "{\"burnTrxAmount\": " + value + "}"; response.getWriter().println(out); } catch (Exception e) { - logger.error("", e); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processServerError(e, response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetContractInfoServlet.java b/framework/src/main/java/org/tron/core/services/http/GetContractInfoServlet.java index 6a1549bd398..76a74dcbf27 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetContractInfoServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetContractInfoServlet.java @@ -38,7 +38,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { response.getWriter().println("{}"); } else { JSONObject jsonSmartContract = JSONObject - .parseObject(JsonFormat.printToString(smartContract, visible)); + .outboundParseObject(JsonFormat.printToString(smartContract, visible)); response.getWriter().println(jsonSmartContract.toJSONString()); } } catch (Exception e) { @@ -66,7 +66,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) response.getWriter().println("{}"); } else { JSONObject jsonSmartContract = JSONObject - .parseObject(JsonFormat.printToString(smartContract, visible)); + .outboundParseObject(JsonFormat.printToString(smartContract, visible)); response.getWriter().println(jsonSmartContract.toJSONString()); } } catch (Exception e) { diff --git a/framework/src/main/java/org/tron/core/services/http/GetContractServlet.java b/framework/src/main/java/org/tron/core/services/http/GetContractServlet.java index 3565d3121f6..bfd014aac20 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetContractServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetContractServlet.java @@ -38,7 +38,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { response.getWriter().println("{}"); } else { JSONObject jsonSmartContract = JSONObject - .parseObject(JsonFormat.printToString(smartContract, visible)); + .outboundParseObject(JsonFormat.printToString(smartContract, visible)); response.getWriter().println(jsonSmartContract.toJSONString()); } } catch (Exception e) { @@ -66,7 +66,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) response.getWriter().println("{}"); } else { JSONObject jsonSmartContract = JSONObject - .parseObject(JsonFormat.printToString(smartContract, visible)); + .outboundParseObject(JsonFormat.printToString(smartContract, visible)); response.getWriter().println(jsonSmartContract.toJSONString()); } } catch (Exception e) { diff --git a/framework/src/main/java/org/tron/core/services/http/GetNodeInfoServlet.java b/framework/src/main/java/org/tron/core/services/http/GetNodeInfoServlet.java index 0b8f7b9ce2b..c8b4aa39785 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetNodeInfoServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetNodeInfoServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -24,12 +23,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { response.getWriter().println(JSON.toJSONString(nodeInfo)); } catch (Exception e) { - logger.error("", e); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processServerError(e, response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetPendingSizeServlet.java b/framework/src/main/java/org/tron/core/services/http/GetPendingSizeServlet.java index 9788c926586..41a47c49001 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetPendingSizeServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetPendingSizeServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -24,12 +23,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { : "{\"pendingSize\": " + value + "}"; response.getWriter().println(out); } catch (Exception e) { - logger.error("", e); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processServerError(e, response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java b/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java index 61b88d1160f..780bab6ac94 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetRewardServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -29,19 +28,9 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { : "{\"reward\": " + value + "}"; response.getWriter().println(out); } catch (DecoderException | IllegalArgumentException e) { - try { - response.getWriter() - .println("{\"Error\": " + "\"INVALID address, " + e.getMessage() + "\"}"); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.writeAuditedError(Util.INVALID_ADDRESS_MSG, response); } catch (Exception e) { - logger.error("", e); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processServerError(e, response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServlet.java b/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServlet.java index 5d0a09b1a68..dce926bf698 100644 --- a/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServlet.java @@ -1,6 +1,5 @@ package org.tron.core.services.http; -import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -29,7 +28,7 @@ private JSONObject convertLogAddressToTronAddress(TransactionInfo transactionInf transactionInfo = transactionInfo.toBuilder().clearLog().addAllLog(newLogList).build(); } - return JSONObject.parseObject(JsonFormat.printToString(transactionInfo, visible)); + return JSONObject.outboundParseObject(JsonFormat.printToString(transactionInfo, visible)); } private String printTransactionInfoList(TransactionInfoList list, boolean selfType) { @@ -52,12 +51,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { response.getWriter().println("{}"); } } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } @@ -75,12 +69,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) response.getWriter().println("{}"); } } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(Util.printErrorMsg(e)); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } } diff --git a/framework/src/main/java/org/tron/core/services/http/JsonFormat.java b/framework/src/main/java/org/tron/core/services/http/JsonFormat.java index 2fa7d9fbb42..e9aa801f078 100644 --- a/framework/src/main/java/org/tron/core/services/http/JsonFormat.java +++ b/framework/src/main/java/org/tron/core/services/http/JsonFormat.java @@ -43,6 +43,7 @@ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT import java.io.IOException; import java.math.BigInteger; import java.nio.CharBuffer; +import java.nio.charset.StandardCharsets; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.Iterator; @@ -929,7 +930,8 @@ private static String escapeNameStringText(String input) { *

  • The following characters are escaped by prefixing them with a '\' : * \b,\f,\n,\r,\t,\,"
  • Other control characters in the range 0x0000-0x001F are escaped * using the \\uXXXX notation
  • UTF-16 surrogate pairs are encoded using the \\uXXXX\\uXXXX - * notation
  • any other character is printed as-is
+ * notation; isolated low surrogates are replaced with '?' as in the legacy UTF-8 writer + *
  • any other character is printed as-is
  • */ static String escapeText(String input) { StringBuilder builder = new StringBuilder(input.length()); @@ -961,6 +963,8 @@ static String escapeText(String input) { // Check for other control characters if (c >= 0x0000 && c <= 0x001F) { appendEscapedUnicode(builder, c); + } else if (Character.isLowSurrogate(c)) { + builder.append(replaceMalformedSurrogates(String.valueOf(c))); } else if (Character.isHighSurrogate(c)) { // Encode the surrogate pair using 2 six-character sequence (\\uXXXX\\uXXXX) appendEscapedUnicode(builder, c); @@ -1046,7 +1050,8 @@ static String unescapeText(String input) throws InvalidEscapeSequence { } break; default: - throw new InvalidEscapeSequence("Invalid escape sequence: '\\" + c + "'"); + throw new InvalidEscapeSequence( + replaceMalformedSurrogates("Invalid escape sequence: '\\" + c + "'")); } } else { throw new InvalidEscapeSequence("Invalid escape sequence: '\\' at end of string."); @@ -1059,6 +1064,14 @@ static String unescapeText(String input) throws InvalidEscapeSequence { return builder.toString(); } + private static String replaceMalformedSurrogates(String value) { + if (value == null) { + return null; + } + // Match the legacy UTF-8 OutputStreamWriter's replacement of malformed surrogates. + return new String(value.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); + } + /** * Is this an octal digit. */ @@ -1719,7 +1732,8 @@ public ByteString consumeByteString(final String fieldName, boolean selfType) */ public ParseException parseException(String description) { // Note: People generally prefer one-based line and column numbers. - return new ParseException((line + 1) + ":" + (column + 1) + ": " + description); + return new ParseException((line + 1) + ":" + (column + 1) + ": " + + replaceMalformedSurrogates(description)); } /** @@ -1729,7 +1743,7 @@ public ParseException parseException(String description) { public ParseException parseExceptionPreviousToken(String description) { // Note: People generally prefer one-based line and column numbers. return new ParseException((previousLine + 1) + ":" + (previousColumn + 1) + ": " - + description); + + replaceMalformedSurrogates(description)); } /** diff --git a/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java b/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java index b5ae7d58623..6f67aba3020 100644 --- a/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java @@ -131,8 +131,7 @@ protected void service(HttpServletRequest req, HttpServletResponse resp) super.service(req, resp); Metrics.histogramObserve(requestTimer); } else { - resp.getWriter() - .println(Util.printErrorMsg(new IllegalAccessException("lack of computing resources"))); + Util.writeAuditedError(Util.RATE_LIMITER_ERROR_MSG, resp); } } catch (ServletException | IOException | BadMessageException e) { throw e; diff --git a/framework/src/main/java/org/tron/core/services/http/ScanAndMarkNoteByIvkServlet.java b/framework/src/main/java/org/tron/core/services/http/ScanAndMarkNoteByIvkServlet.java index b91fd394442..f96f77bfb81 100644 --- a/framework/src/main/java/org/tron/core/services/http/ScanAndMarkNoteByIvkServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/ScanAndMarkNoteByIvkServlet.java @@ -27,7 +27,7 @@ private String convertOutput(GrpcAPI.DecryptNotesMarked notes, boolean visible) if (notes.getNoteTxsCount() == 0) { return resultString; } else { - JSONObject markedNotes = JSONObject.parseObject(resultString); + JSONObject markedNotes = JSONObject.outboundParseObject(resultString); JSONArray array = markedNotes.getJSONArray("noteTxs"); for (int index = 0; index < array.size(); index++) { JSONObject item = array.getJSONObject(index); diff --git a/framework/src/main/java/org/tron/core/services/http/ScanNoteByIvkServlet.java b/framework/src/main/java/org/tron/core/services/http/ScanNoteByIvkServlet.java index c8e25a2fc37..bd1c92d13ec 100644 --- a/framework/src/main/java/org/tron/core/services/http/ScanNoteByIvkServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/ScanNoteByIvkServlet.java @@ -25,7 +25,7 @@ public static String convertOutput(GrpcAPI.DecryptNotes notes, boolean visible) if (notes.getNoteTxsCount() == 0) { return resultString; } else { - JSONObject jsonNotes = JSONObject.parseObject(resultString); + JSONObject jsonNotes = JSONObject.outboundParseObject(resultString); JSONArray array = jsonNotes.getJSONArray("noteTxs"); for (int index = 0; index < array.size(); index++) { JSONObject item = array.getJSONObject(index); diff --git a/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByIvkServlet.java b/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByIvkServlet.java index d9da2453c9b..f3b4dbb884d 100644 --- a/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByIvkServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/ScanShieldedTRC20NotesByIvkServlet.java @@ -24,7 +24,7 @@ public static String convertOutput(GrpcAPI.DecryptNotesTRC20 notes, boolean visi if (notes.getNoteTxsCount() == 0) { return resultString; } else { - JSONObject jsonNotes = JSONObject.parseObject(resultString); + JSONObject jsonNotes = JSONObject.outboundParseObject(resultString); JSONArray array = jsonNotes.getJSONArray("noteTxs"); for (int index = 0; index < array.size(); index++) { JSONObject item = array.getJSONObject(index); diff --git a/framework/src/main/java/org/tron/core/services/http/Util.java b/framework/src/main/java/org/tron/core/services/http/Util.java index 5be2495e1f7..13bbca8613c 100644 --- a/framework/src/main/java/org/tron/core/services/http/Util.java +++ b/framework/src/main/java/org/tron/core/services/http/Util.java @@ -36,7 +36,6 @@ import org.tron.api.GrpcAPI.TransactionApprovedList; import org.tron.api.GrpcAPI.TransactionExtention; import org.tron.api.GrpcAPI.TransactionIdList; -import org.tron.api.GrpcAPI.TransactionList; import org.tron.api.GrpcAPI.TransactionSignWeight; import org.tron.common.crypto.Hash; import org.tron.common.parameter.CommonParameter; @@ -48,6 +47,8 @@ import org.tron.core.capsule.TransactionCapsule; import org.tron.core.config.args.Args; import org.tron.core.db.TransactionTrace; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.MaintenanceUnavailableException; import org.tron.core.services.http.JsonFormat.ParseException; import org.tron.json.JSON; import org.tron.json.JSONArray; @@ -65,6 +66,10 @@ @Slf4j(topic = "API") public class Util { + private static final String INTERNAL_SERVER_ERROR = "internal server error"; + public static final String RATE_LIMITER_ERROR_MSG = "lack of computing resources"; + static final String INVALID_ADDRESS_MSG = "INVALID address"; + public static final String EVENTS_DEPRECATED_MSG = "'events' field is deprecated and no longer supported"; @@ -109,17 +114,36 @@ public static void rejectIfEventsPresent(String[] eventsParams) { public static String printTransactionFee(String transactionFee) { JSONObject jsonObject = new JSONObject(); - JSONObject receipt = JSONObject.parseObject(transactionFee); + JSONObject receipt = JSONObject.outboundParseObject(transactionFee); jsonObject.put("Receipt", receipt.get("receipt")); return jsonObject.toJSONString(); } - public static String printErrorMsg(Exception e) { + private static String printErrorMsg(String msg) { JSONObject jsonObject = new JSONObject(); - jsonObject.put("Error", e.getClass() + " : " + e.getMessage()); + jsonObject.put("Error", msg); return jsonObject.toJSONString(); } + private static String clientMessage(Exception e) { + if (e == null) { + return INTERNAL_SERVER_ERROR; + } + + Class type = e.getClass(); + if (type == IllegalArgumentException.class) { + return EVENTS_DEPRECATED_MSG.equals(e.getMessage()) + ? EVENTS_DEPRECATED_MSG : INTERNAL_SERVER_ERROR; + } + if (type == ParseException.class + || type == ContractValidateException.class + || type == MaintenanceUnavailableException.class) { + String message = e.getMessage(); + return StringUtils.isBlank(message) ? INTERNAL_SERVER_ERROR : message; + } + return INTERNAL_SERVER_ERROR; + } + public static String printBlockList(BlockList list, boolean selfType) { List blocks = list.getBlockList(); JSONObject jsonObject = new JSONObject(); @@ -140,7 +164,7 @@ public static JSONObject printBlockToJSON(Block block, boolean selfType) { JSONObject jsonObject = new JSONObject(); jsonObject.put("blockID", blockID); jsonObject.put("block_header", - JSONObject.parseObject(JsonFormat.printToString(block.getBlockHeader(), selfType))); + JSONObject.outboundParseObject(JsonFormat.printToString(block.getBlockHeader(), selfType))); if (!blockCapsule.getTransactions().isEmpty()) { jsonObject.put("transactions", printTransactionListToJSON(blockCapsule.getTransactions(), selfType)); @@ -148,19 +172,9 @@ public static JSONObject printBlockToJSON(Block block, boolean selfType) { return jsonObject; } - public static String printTransactionList(TransactionList list, boolean selfType) { - List transactions = list.getTransactionList(); - JSONObject jsonObject = JSONObject.parseObject(JsonFormat.printToString(list, selfType)); - JSONArray jsonArray = new JSONArray(); - transactions.stream() - .forEach(transaction -> jsonArray.add(printTransactionToJSON(transaction, selfType))); - jsonObject.put(TRANSACTION, jsonArray); - - return jsonObject.toJSONString(); - } - public static String printTransactionIdList(TransactionIdList list, boolean selfType) { - JSONObject jsonObject = JSONObject.parseObject(JsonFormat.printToString(list, selfType)); + JSONObject jsonObject = JSONObject.outboundParseObject( + JsonFormat.printToString(list, selfType)); return jsonObject.toJSONString(); } @@ -190,7 +204,7 @@ public static String printCreateTransaction(Transaction transaction, boolean sel public static String printTransactionExtention(TransactionExtention transactionExtention, boolean selfType) { String string = JsonFormat.printToString(transactionExtention, selfType); - JSONObject jsonObject = JSONObject.parseObject(string); + JSONObject jsonObject = JSONObject.outboundParseObject(string); if (transactionExtention.getResult().getResult()) { JSONObject transactionObject = printTransactionToJSON(transactionExtention.getTransaction(), selfType); @@ -208,7 +222,7 @@ public static String printEstimateEnergyMessage(GrpcAPI.EstimateEnergyMessage me public static String printTransactionSignWeight(TransactionSignWeight transactionSignWeight, boolean selfType) { String string = JsonFormat.printToString(transactionSignWeight, selfType); - JSONObject jsonObject = JSONObject.parseObject(string); + JSONObject jsonObject = JSONObject.outboundParseObject(string); JSONObject jsonObjectExt = jsonObject.getJSONObject(TRANSACTION); if (jsonObjectExt != null) { jsonObjectExt.put(TRANSACTION, @@ -222,7 +236,7 @@ public static String printTransactionSignWeight(TransactionSignWeight transactio public static String printTransactionApprovedList(TransactionApprovedList transactionApprovedList, boolean selfType) { String string = JsonFormat.printToString(transactionApprovedList, selfType); - JSONObject jsonObject = JSONObject.parseObject(string); + JSONObject jsonObject = JSONObject.outboundParseObject(string); JSONObject jsonObjectExt = jsonObject.getJSONObject(TRANSACTION); if (jsonObjectExt != null) { jsonObjectExt.put(TRANSACTION, @@ -249,7 +263,7 @@ public static byte[] generateContractAddress(Transaction trx, byte[] ownerAddres public static JSONObject printTransactionToJSON(Transaction transaction, boolean selfType) { JSONObject jsonTransaction = JSONObject - .parseObject(JsonFormat.printToString(transaction, selfType)); + .outboundParseObject(JsonFormat.printToString(transaction, selfType)); JSONArray contracts = new JSONArray(); transaction.getRawData().getContractList().stream().forEach(contract -> { try { @@ -260,7 +274,7 @@ public static JSONObject printTransactionToJSON(Transaction transaction, boolean CreateSmartContract deployContract = contractParameter .unpack(CreateSmartContract.class); contractJson = JSONObject - .parseObject(JsonFormat.printToString(deployContract, selfType)); + .outboundParseObject(JsonFormat.printToString(deployContract, selfType)); byte[] ownerAddress = deployContract.getOwnerAddress().toByteArray(); byte[] contractAddress = generateContractAddress(transaction, ownerAddress); jsonTransaction.put(CONTRACT_ADDRESS, ByteArray.toHexString(contractAddress)); @@ -268,8 +282,9 @@ public static JSONObject printTransactionToJSON(Transaction transaction, boolean default: Class clazz = TransactionFactory.getContract(contract.getType()); if (clazz != null) { - contractJson = JSONObject - .parseObject(JsonFormat.printToString(contractParameter.unpack(clazz), selfType)); + String parameterJson = JsonFormat.printToString( + contractParameter.unpack(clazz), selfType); + contractJson = JSONObject.outboundParseObject(parameterJson); } break; } @@ -289,9 +304,8 @@ public static JSONObject printTransactionToJSON(Transaction transaction, boolean } }); - JSONObject rawData = JSONObject.parseObject(jsonTransaction.get("raw_data").toString()); + JSONObject rawData = jsonTransaction.getJSONObject("raw_data"); rawData.put("contract", contracts); - jsonTransaction.put("raw_data", rawData); String rawDataHex = ByteArray.toHexString(transaction.getRawData().toByteArray()); jsonTransaction.put("raw_data_hex", rawDataHex); String txID = ByteArray.toHexString(Sha256Hash @@ -526,11 +540,24 @@ public static String getMemo(byte[] memo) { } public static void processError(Exception e, HttpServletResponse response) { - logger.debug(e.getMessage(), e); + logger.debug("HTTP request failed", e); + writeAuditedError(clientMessage(e), response); + } + + // For catch blocks that cover server-side work only, so the failure stays visible at the + // default log level. The Exception entry point above keeps debug because its callers also + // cover request parsing, which an unauthenticated client can fail cheaply and repeatedly. + static void processServerError(Exception e, HttpServletResponse response) { + logger.error("HTTP request failed", e); + writeAuditedError(clientMessage(e), response); + } + + // Bypasses clientMessage: callers must pass audited fixed or pre-existing client texts only. + static void writeAuditedError(String msg, HttpServletResponse response) { try { - response.getWriter().println(Util.printErrorMsg(e)); + response.getWriter().println(Util.printErrorMsg(msg)); } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); + logger.debug("Failed to write HTTP error response", ioe); } } @@ -538,7 +565,8 @@ public static String convertOutput(Account account) { if (account.getAssetIssuedID().isEmpty()) { return JsonFormat.printToString(account, false); } else { - JSONObject accountJson = JSONObject.parseObject(JsonFormat.printToString(account, false)); + JSONObject accountJson = JSONObject.outboundParseObject( + JsonFormat.printToString(account, false)); String assetId = accountJson.get("asset_issued_ID").toString(); accountJson.put("asset_issued_ID", ByteString.copyFrom(ByteArray.fromHexString(assetId)).toStringUtf8()); diff --git a/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java b/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java index 07eecfc5466..3ef45b42a7e 100644 --- a/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/ValidateAddressServlet.java @@ -47,7 +47,7 @@ private String validAddress(String input) { } } catch (Exception e) { result = false; - msg = e.getMessage(); + msg = "Invalid address"; } JSONObject jsonAddress = new JSONObject(); diff --git a/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServlet.java b/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServlet.java index f98c7450afc..5998bc0850f 100644 --- a/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServlet.java @@ -30,12 +30,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { String input = request.getParameter("value"); fillResponse(ByteString.copyFrom(ByteArray.fromHexString(input)), visible, response); } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(e.getMessage()); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } @@ -46,12 +41,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) JsonFormat.merge(params.getParams(), build, params.isVisible()); fillResponse(build.build().getValue(), params.isVisible(), response); } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(e.getMessage()); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } diff --git a/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServlet.java b/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServlet.java index 0408215f09d..197f5aaec0d 100644 --- a/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServlet.java @@ -1,7 +1,6 @@ package org.tron.core.services.http.solidity; import com.google.protobuf.ByteString; -import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; @@ -37,12 +36,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) { response.getWriter().println(JsonFormat.printToString(transInfo, visible)); } } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(e.getMessage()); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } @@ -60,12 +54,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) response.getWriter().println(JsonFormat.printToString(transInfo, params.isVisible())); } } catch (Exception e) { - logger.debug("Exception: {}", e.getMessage()); - try { - response.getWriter().println(e.getMessage()); - } catch (IOException ioe) { - logger.debug("IOException: {}", ioe.getMessage()); - } + Util.processError(e, response); } } diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java index 54e7b69f7fc..2e6d1bd59bd 100755 --- a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java @@ -1,67 +1,22 @@ package org.tron.core.services.interfaceOnPBFT; +import io.grpc.ServerInterceptors; import io.grpc.netty.NettyServerBuilder; -import io.grpc.stub.StreamObserver; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.tron.api.DatabaseGrpc.DatabaseImplBase; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.GrpcAPI.BlockExtention; -import org.tron.api.GrpcAPI.BlockReference; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.CanDelegatedMaxSizeRequestMessage; -import org.tron.api.GrpcAPI.CanDelegatedMaxSizeResponseMessage; -import org.tron.api.GrpcAPI.CanWithdrawUnfreezeAmountRequestMessage; -import org.tron.api.GrpcAPI.CanWithdrawUnfreezeAmountResponseMessage; -import org.tron.api.GrpcAPI.DecryptNotesTRC20; -import org.tron.api.GrpcAPI.DelegatedResourceList; -import org.tron.api.GrpcAPI.DelegatedResourceMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.GetAvailableUnfreezeCountRequestMessage; -import org.tron.api.GrpcAPI.GetAvailableUnfreezeCountResponseMessage; -import org.tron.api.GrpcAPI.IvkDecryptTRC20Parameters; -import org.tron.api.GrpcAPI.NfTRC20Parameters; -import org.tron.api.GrpcAPI.NoteParameters; -import org.tron.api.GrpcAPI.NullifierResult; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.OvkDecryptTRC20Parameters; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.GrpcAPI.PricesResponseMessage; -import org.tron.api.GrpcAPI.SpendResult; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletSolidityGrpc.WalletSolidityImplBase; import org.tron.common.application.RpcService; import org.tron.core.config.args.Args; import org.tron.core.services.RpcApiService; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.DelegatedResourceAccountIndex; -import org.tron.protos.Protocol.DynamicProperties; -import org.tron.protos.Protocol.Exchange; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.MarketOrderPair; -import org.tron.protos.Protocol.MarketOrderPairList; -import org.tron.protos.Protocol.MarketPriceList; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; - +import org.tron.core.services.filter.PbftCursorInterceptor; @Slf4j(topic = "API") public class RpcApiServiceOnPBFT extends RpcService { @Autowired - private WalletOnPBFT walletOnPBFT; + private RpcApiService rpcApiService; @Autowired - private RpcApiService rpcApiService; + private PbftCursorInterceptor pbftCursorInterceptor; public RpcApiServiceOnPBFT() { port = Args.getInstance().getRpcOnPBFTPort(); @@ -69,427 +24,13 @@ public RpcApiServiceOnPBFT() { executorName = "rpc-pbft-executor"; } + /** PBFT cursor bound at the service level, so it brackets only these two read services. */ @Override protected void addService(NettyServerBuilder serverBuilder) { - serverBuilder.addService(new DatabaseApi()); - serverBuilder.addService(new WalletPBFTApi()); + serverBuilder.addService( + ServerInterceptors.intercept(rpcApiService.getDatabaseApi(), pbftCursorInterceptor)); + serverBuilder.addService(ServerInterceptors.intercept( + rpcApiService.getWalletSolidityApi(), pbftCursorInterceptor)); } - /** - * DatabaseApi. - */ - private class DatabaseApi extends DatabaseImplBase { - - @Override - public void getBlockReference(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getDatabaseApi().getBlockReference(request, responseObserver) - ); - } - - @Override - public void getNowBlock(EmptyMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getDatabaseApi().getNowBlock(request, responseObserver)); - } - - @Override - public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getDatabaseApi().getBlockByNum(request, responseObserver) - ); - } - - @Override - public void getDynamicProperties(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getDatabaseApi().getDynamicProperties(request, responseObserver) - ); - } - } - - /** - * WalletPBFTApi. - */ - private class WalletPBFTApi extends WalletSolidityImplBase { - - @Override - public void getAccount(Account request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAccount(request, responseObserver) - ); - } - - @Override - public void getAccountById(Account request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAccountById(request, responseObserver) - ); - } - - @Override - public void listWitnesses(EmptyMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().listWitnesses(request, responseObserver) - ); - } - - @Override - public void getAssetIssueById(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAssetIssueById(request, responseObserver) - ); - } - - @Override - public void getAssetIssueByName(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAssetIssueByName(request, responseObserver) - ); - } - - @Override - public void getAssetIssueList(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAssetIssueList(request, responseObserver) - ); - } - - @Override - public void getAssetIssueListByName(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getAssetIssueListByName(request, responseObserver) - ); - } - - @Override - public void getPaginatedAssetIssueList(PaginatedMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getPaginatedAssetIssueList(request, responseObserver) - ); - } - - @Override - public void getExchangeById(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getExchangeById( - request, responseObserver - ) - ); - } - - @Override - public void getNowBlock(EmptyMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getNowBlock(request, responseObserver) - ); - } - - @Override - public void getNowBlock2(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getNowBlock2(request, responseObserver) - ); - - } - - @Override - public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlockByNum(request, responseObserver) - ); - } - - @Override - public void getBlockByNum2(NumberMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlockByNum2(request, responseObserver) - ); - } - - @Override - public void getDelegatedResource(DelegatedResourceMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getDelegatedResource(request, responseObserver) - ); - } - - @Override - public void getDelegatedResourceV2(DelegatedResourceMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceV2(request, responseObserver) - ); - } - - @Override - public void getDelegatedResourceAccountIndex(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceAccountIndex(request, responseObserver) - ); - } - - @Override - public void getDelegatedResourceAccountIndexV2(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceAccountIndexV2(request, responseObserver) - ); - } - - @Override - public void getCanDelegatedMaxSize(CanDelegatedMaxSizeRequestMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getCanDelegatedMaxSize(request, responseObserver) - ); - } - - @Override - public void getAvailableUnfreezeCount(GetAvailableUnfreezeCountRequestMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getAvailableUnfreezeCount(request, responseObserver) - ); - } - - @Override - public void getCanWithdrawUnfreezeAmount(CanWithdrawUnfreezeAmountRequestMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getCanWithdrawUnfreezeAmount(request, responseObserver) - ); - } - - @Override - public void getTransactionCountByBlockNum(NumberMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getTransactionCountByBlockNum(request, responseObserver) - ); - } - - @Override - public void getTransactionById(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getTransactionById(request, responseObserver) - ); - - } - - @Override - public void getTransactionInfoById(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getTransactionInfoById(request, responseObserver) - ); - - } - - @Override - public void listExchanges(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().listExchanges(request, responseObserver) - ); - } - - @Override - public void triggerConstantContract(TriggerSmartContract request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .triggerConstantContract(request, responseObserver) - ); - } - - @Override - public void estimateEnergy(TriggerSmartContract request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .estimateEnergy(request, responseObserver) - ); - } - - @Override - public void getRewardInfo(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getRewardInfo(request, responseObserver) - ); - } - - @Override - public void getBrokerageInfo(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBrokerageInfo(request, responseObserver) - ); - } - - @Override - public void getMerkleTreeVoucherInfo(OutputPointInfo request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMerkleTreeVoucherInfo(request, responseObserver) - ); - } - - @Override - public void scanNoteByIvk(GrpcAPI.IvkDecryptParameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().scanNoteByIvk(request, responseObserver) - ); - } - - @Override - public void scanAndMarkNoteByIvk(GrpcAPI.IvkDecryptAndMarkParameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().scanAndMarkNoteByIvk(request, responseObserver) - ); - } - - @Override - public void scanNoteByOvk(GrpcAPI.OvkDecryptParameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().scanNoteByOvk(request, responseObserver) - ); - } - - @Override - public void isSpend(NoteParameters request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().isSpend(request, responseObserver) - ); - } - - @Override - public void getMarketOrderByAccount(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderByAccount(request, responseObserver) - ); - } - - @Override - public void getMarketOrderById(BytesMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderById(request, responseObserver) - ); - } - - @Override - public void getMarketPriceByPair(MarketOrderPair request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketPriceByPair(request, responseObserver) - ); - } - - @Override - public void getMarketOrderListByPair(MarketOrderPair request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderListByPair(request, responseObserver) - ); - } - - @Override - public void getMarketPairList(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketPairList(request, responseObserver) - ); - } - - @Override - public void scanShieldedTRC20NotesByIvk(IvkDecryptTRC20Parameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .scanShieldedTRC20NotesByIvk(request, responseObserver) - ); - } - - @Override - public void scanShieldedTRC20NotesByOvk(OvkDecryptTRC20Parameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .scanShieldedTRC20NotesByOvk(request, responseObserver) - ); - } - - @Override - public void isShieldedTRC20ContractNoteSpent(NfTRC20Parameters request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .isShieldedTRC20ContractNoteSpent(request, responseObserver) - ); - } - - @Override - public void getBurnTrx(EmptyMessage request, StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBurnTrx(request, responseObserver) - ); - } - - @Override - public void getBlock(GrpcAPI.BlockReq request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlock(request, responseObserver)); - } - - @Override - public void getBandwidthPrices(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBandwidthPrices(request, responseObserver)); - } - - @Override - public void getEnergyPrices(EmptyMessage request, - StreamObserver responseObserver) { - walletOnPBFT.futureGet( - () -> rpcApiService.getWalletSolidityApi().getEnergyPrices(request, responseObserver)); - } - - } } diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java index 315d70df8d6..f0c7b1468d2 100755 --- a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java @@ -1,70 +1,22 @@ package org.tron.core.services.interfaceOnSolidity; -import com.google.protobuf.ByteString; +import io.grpc.ServerInterceptors; import io.grpc.netty.NettyServerBuilder; -import io.grpc.stub.StreamObserver; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.tron.api.DatabaseGrpc.DatabaseImplBase; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.GrpcAPI.BlockExtention; -import org.tron.api.GrpcAPI.BlockReference; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.CanDelegatedMaxSizeRequestMessage; -import org.tron.api.GrpcAPI.CanDelegatedMaxSizeResponseMessage; -import org.tron.api.GrpcAPI.CanWithdrawUnfreezeAmountRequestMessage; -import org.tron.api.GrpcAPI.CanWithdrawUnfreezeAmountResponseMessage; -import org.tron.api.GrpcAPI.DelegatedResourceList; -import org.tron.api.GrpcAPI.DelegatedResourceMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.GetAvailableUnfreezeCountRequestMessage; -import org.tron.api.GrpcAPI.GetAvailableUnfreezeCountResponseMessage; -import org.tron.api.GrpcAPI.NoteParameters; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.GrpcAPI.PricesResponseMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.GrpcAPI.SpendResult; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.TransactionInfoList; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletSolidityGrpc.WalletSolidityImplBase; import org.tron.common.application.RpcService; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.Sha256Hash; -import org.tron.core.capsule.BlockCapsule; import org.tron.core.config.args.Args; import org.tron.core.services.RpcApiService; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.DelegatedResourceAccountIndex; -import org.tron.protos.Protocol.DynamicProperties; -import org.tron.protos.Protocol.Exchange; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.MarketOrderPair; -import org.tron.protos.Protocol.MarketOrderPairList; -import org.tron.protos.Protocol.MarketPriceList; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; - +import org.tron.core.services.filter.SolidityCursorInterceptor; @Slf4j(topic = "API") public class RpcApiServiceOnSolidity extends RpcService { - @Autowired - private WalletOnSolidity walletOnSolidity; + private RpcApiService rpcApiService; @Autowired - private RpcApiService rpcApiService; + private SolidityCursorInterceptor solidityCursorInterceptor; public RpcApiServiceOnSolidity() { port = Args.getInstance().getRpcOnSolidityPort(); @@ -72,417 +24,13 @@ public RpcApiServiceOnSolidity() { executorName = "rpc-solidity-executor"; } + /** SOLIDITY cursor bound at the service level, so it brackets only these two read services. */ @Override protected void addService(NettyServerBuilder serverBuilder) { - serverBuilder.addService(new DatabaseApi()); - serverBuilder.addService(new WalletSolidityApi()); + serverBuilder.addService( + ServerInterceptors.intercept(rpcApiService.getDatabaseApi(), solidityCursorInterceptor)); + serverBuilder.addService(ServerInterceptors.intercept( + rpcApiService.getWalletSolidityApi(), solidityCursorInterceptor)); } - private TransactionExtention transaction2Extention(Transaction transaction) { - if (transaction == null) { - return null; - } - TransactionExtention.Builder trxExtBuilder = TransactionExtention.newBuilder(); - Return.Builder retBuilder = Return.newBuilder(); - trxExtBuilder.setTransaction(transaction); - trxExtBuilder.setTxid(Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()).getByteString()); - retBuilder.setResult(true).setCode(response_code.SUCCESS); - trxExtBuilder.setResult(retBuilder); - return trxExtBuilder.build(); - } - - private BlockExtention block2Extention(Block block) { - if (block == null) { - return null; - } - BlockExtention.Builder builder = BlockExtention.newBuilder(); - BlockCapsule blockCapsule = new BlockCapsule(block); - builder.setBlockHeader(block.getBlockHeader()); - builder.setBlockid(ByteString.copyFrom(blockCapsule.getBlockId().getBytes())); - for (int i = 0; i < block.getTransactionsCount(); i++) { - Transaction transaction = block.getTransactions(i); - builder.addTransactions(transaction2Extention(transaction)); - } - return builder.build(); - } - - /** - * DatabaseApi. - */ - private class DatabaseApi extends DatabaseImplBase { - - @Override - public void getBlockReference(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getDatabaseApi().getBlockReference(request, responseObserver)); - } - - @Override - public void getNowBlock(EmptyMessage request, StreamObserver responseObserver) { - walletOnSolidity - .futureGet(() -> rpcApiService.getDatabaseApi().getNowBlock(request, responseObserver)); - } - - @Override - public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - walletOnSolidity - .futureGet(() -> rpcApiService.getDatabaseApi().getBlockByNum(request, responseObserver)); - } - - @Override - public void getDynamicProperties(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getDatabaseApi().getDynamicProperties(request, responseObserver)); - } - } - - /** - * WalletSolidityApi. - */ - private class WalletSolidityApi extends WalletSolidityImplBase { - - @Override - public void getAccount(Account request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAccount(request, responseObserver)); - } - - @Override - public void getAccountById(Account request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAccountById(request, responseObserver)); - } - - @Override - public void listWitnesses(EmptyMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().listWitnesses(request, responseObserver)); - } - - public void getPaginatedNowWitnessList(PaginatedMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getPaginatedNowWitnessList(request, responseObserver)); - } - - @Override - public void getAssetIssueById(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAssetIssueById(request, responseObserver)); - } - - @Override - public void getAssetIssueByName(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getAssetIssueByName(request, responseObserver)); - } - - @Override - public void getAssetIssueList(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getAssetIssueList(request, responseObserver)); - } - - @Override - public void getAssetIssueListByName(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getAssetIssueListByName(request, responseObserver)); - } - - @Override - public void getPaginatedAssetIssueList(PaginatedMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getPaginatedAssetIssueList(request, responseObserver)); - } - - @Override - public void getExchangeById(BytesMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getExchangeById(request, responseObserver)); - } - - @Override - public void getNowBlock(EmptyMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getNowBlock(request, responseObserver)); - } - - @Override - public void getNowBlock2(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getNowBlock2(request, responseObserver)); - - } - - @Override - public void getBlockByNum(NumberMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlockByNum(request, responseObserver)); - } - - @Override - public void getBlockByNum2(NumberMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlockByNum2(request, responseObserver)); - } - - @Override - public void getDelegatedResource(DelegatedResourceMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getDelegatedResource(request, responseObserver)); - } - - @Override - public void getDelegatedResourceV2(DelegatedResourceMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceV2(request, responseObserver)); - } - - @Override - public void getDelegatedResourceAccountIndex(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceAccountIndex(request, responseObserver)); - } - - @Override - public void getDelegatedResourceAccountIndexV2(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getDelegatedResourceAccountIndexV2(request, responseObserver)); - } - - @Override - public void getCanDelegatedMaxSize(CanDelegatedMaxSizeRequestMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getCanDelegatedMaxSize(request, responseObserver)); - } - - @Override - public void getAvailableUnfreezeCount(GetAvailableUnfreezeCountRequestMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getAvailableUnfreezeCount(request, responseObserver)); - } - - @Override - public void getCanWithdrawUnfreezeAmount(CanWithdrawUnfreezeAmountRequestMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getCanWithdrawUnfreezeAmount(request, responseObserver)); - } - - @Override - public void getTransactionCountByBlockNum(NumberMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getTransactionCountByBlockNum(request, responseObserver)); - } - - @Override - public void getTransactionById(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getTransactionById(request, responseObserver)); - - } - - @Override - public void getTransactionInfoById(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getTransactionInfoById(request, responseObserver)); - - } - - @Override - public void listExchanges(EmptyMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().listExchanges(request, responseObserver)); - } - - @Override - public void triggerConstantContract(TriggerSmartContract request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .triggerConstantContract(request, responseObserver)); - } - - @Override - public void estimateEnergy(TriggerSmartContract request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .estimateEnergy(request, responseObserver)); - } - - @Override - public void getRewardInfo(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getRewardInfo(request, responseObserver)); - } - - @Override - public void getBrokerageInfo(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBrokerageInfo(request, responseObserver)); - } - - @Override - public void getMerkleTreeVoucherInfo(OutputPointInfo request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getMerkleTreeVoucherInfo(request, responseObserver)); - } - - @Override - public void scanNoteByIvk(GrpcAPI.IvkDecryptParameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().scanNoteByIvk(request, responseObserver)); - } - - @Override - public void scanAndMarkNoteByIvk(GrpcAPI.IvkDecryptAndMarkParameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .scanAndMarkNoteByIvk(request, responseObserver)); - } - - @Override - public void scanNoteByOvk(GrpcAPI.OvkDecryptParameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().scanNoteByOvk(request, responseObserver)); - } - - @Override - public void isSpend(NoteParameters request, StreamObserver responseObserver) { - walletOnSolidity - .futureGet(() -> rpcApiService.getWalletSolidityApi().isSpend(request, responseObserver)); - } - - @Override - public void getTransactionInfoByBlockNum(NumberMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet(() -> rpcApiService.getWalletSolidityApi() - .getTransactionInfoByBlockNum(request, responseObserver)); - } - - @Override - public void scanShieldedTRC20NotesByIvk(GrpcAPI.IvkDecryptTRC20Parameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .scanShieldedTRC20NotesByIvk(request, responseObserver) - ); - } - - @Override - public void scanShieldedTRC20NotesByOvk(GrpcAPI.OvkDecryptTRC20Parameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .scanShieldedTRC20NotesByOvk(request, responseObserver) - ); - } - - @Override - public void isShieldedTRC20ContractNoteSpent(GrpcAPI.NfTRC20Parameters request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .isShieldedTRC20ContractNoteSpent(request, responseObserver) - ); - } - - @Override - public void getMarketOrderByAccount(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderByAccount(request, responseObserver) - ); - } - - @Override - public void getMarketOrderById(BytesMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderById(request, responseObserver) - ); - } - - @Override - public void getMarketPriceByPair(MarketOrderPair request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketPriceByPair(request, responseObserver) - ); - } - - @Override - public void getMarketOrderListByPair(org.tron.protos.Protocol.MarketOrderPair request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketOrderListByPair(request, responseObserver) - ); - } - - @Override - public void getMarketPairList(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi() - .getMarketPairList(request, responseObserver) - ); - } - - @Override - public void getBurnTrx(EmptyMessage request, StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBurnTrx(request, responseObserver) - ); - } - - @Override - public void getBlock(GrpcAPI.BlockReq request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBlock(request, responseObserver)); - } - - @Override - public void getBandwidthPrices(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getBandwidthPrices(request, responseObserver)); - } - - @Override - public void getEnergyPrices(EmptyMessage request, - StreamObserver responseObserver) { - walletOnSolidity.futureGet( - () -> rpcApiService.getWalletSolidityApi().getEnergyPrices(request, responseObserver)); - } - - } } diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java index 33e325bd578..b7e96a36b45 100644 --- a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java @@ -265,7 +265,6 @@ protected void addServlet(ServletContextHandler context) { context.addServlet(new ServletHolder(getMarketPairListOnSolidityServlet), "/walletsolidity/getmarketpairlist"); - // only for SolidityNode context.addServlet(new ServletHolder(getTransactionByIdOnSolidityServlet), "/walletsolidity/gettransactionbyid"); context.addServlet(new ServletHolder(getTransactionInfoByIdOnSolidityServlet), diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java index ca249da4e5d..6f66a0b2c70 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java @@ -35,6 +35,7 @@ public class JsonRpcServlet extends RateLimiterServlet { private static final ObjectMapper MAPPER = buildMapper(); + private static final ObjectMapper OUTBOUND_MAPPER = new ObjectMapper(); private static ObjectMapper buildMapper() { JsonFactory factory = JsonFactory.builder() @@ -241,7 +242,7 @@ private void handleBatch(HttpServletResponse resp, JsonNode rootNode, int maxRes JsonNode responseNode; try { - responseNode = MAPPER.readTree(responseBytes); + responseNode = OUTBOUND_MAPPER.readTree(responseBytes); } catch (IOException e) { writeJsonRpcError(resp, JsonRpcError.INTERNAL_ERROR, "Internal error", null, true); return; diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java b/framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java index 6be47886117..ef1141c8f69 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java @@ -20,10 +20,10 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; +import com.google.common.util.concurrent.Uninterruptibles; import com.google.protobuf.ByteString; import com.google.protobuf.GeneratedMessageV3; import java.io.Closeable; -import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -36,7 +36,9 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; +import javax.annotation.PostConstruct; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -53,7 +55,9 @@ import org.tron.common.es.ExecutorServiceManager; import org.tron.common.logsfilter.ContractEventParser; import org.tron.common.logsfilter.capsule.BlockFilterCapsule; +import org.tron.common.logsfilter.capsule.FilterTriggerCapsule; import org.tron.common.logsfilter.capsule.LogsFilterCapsule; +import org.tron.common.logsfilter.queue.FilterCapsuleQueue; import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.vm.DataWord; import org.tron.common.utils.ByteArray; @@ -93,7 +97,7 @@ import org.tron.core.services.jsonrpc.types.TransactionResult; import org.tron.core.store.StorageRowStore; import org.tron.core.vm.program.Storage; -import org.tron.json.JSON; +import org.tron.json.JSONObject; import org.tron.program.Version; import org.tron.protos.Protocol.Account; import org.tron.protos.Protocol.Block; @@ -193,20 +197,50 @@ public enum RequestSource { private final ExecutorService sectionExecutor; private final NodeInfoService nodeInfoService; private final Wallet wallet; - @Autowired - private Manager manager; + private final Manager manager; private final String esName = "query-section"; @Autowired - public TronJsonRpcImpl(@Autowired NodeInfoService nodeInfoService, @Autowired Wallet wallet) { + private FilterCapsuleQueue filterCapsuleQueue; + private ExecutorService filterEs; + private static final String filterEsName = "filter"; + private final AtomicBoolean closed = new AtomicBoolean(false); + + @Autowired + public TronJsonRpcImpl(NodeInfoService nodeInfoService, Wallet wallet, Manager manager) { this.nodeInfoService = nodeInfoService; this.wallet = wallet; + this.manager = manager; this.sectionExecutor = ExecutorServiceManager.newFixedThreadPool(esName, 5); } - @VisibleForTesting - public void setManager(Manager manager) { - this.manager = manager; + @PostConstruct + private void start() { + if (CommonParameter.getInstance().isJsonRpcFilterEnabled()) { + filterEs = ExecutorServiceManager.newSingleThreadExecutor(filterEsName, true); + ExecutorServiceManager.submit(filterEs, this::filterProcessLoop); + } + } + + private void filterProcessLoop() { + while (!closed.get()) { + try { + FilterTriggerCapsule filterCapsule = filterCapsuleQueue.poll(1, TimeUnit.SECONDS); + if (filterCapsule instanceof LogsFilterCapsule) { + handleLogsFilter((LogsFilterCapsule) filterCapsule); + } else if (filterCapsule instanceof BlockFilterCapsule) { + handleBLockFilter((BlockFilterCapsule) filterCapsule); + } else if (filterCapsule != null) { + logger.warn("Unknown FilterTriggerCapsule: {}", filterCapsule.getClass().getName()); + } + } catch (InterruptedException e) { + logger.error("FilterProcessLoop get InterruptedException, error is {}.", e.getMessage()); + Thread.currentThread().interrupt(); + return; + } catch (Throwable throwable) { + logger.error("Unknown throwable happened in filterProcessLoop. ", throwable); + } + } } @VisibleForTesting @@ -627,7 +661,8 @@ public String getStorageAt(String address, String storageIdx, String blockNumOrT } StorageRowStore store = manager.getStorageRowStore(); - Storage storage = new Storage(addressByte, store); + Storage storage = new Storage(addressByte, store, + manager.getDynamicPropertiesStore().allowOptimizeTvmStorage()); storage.setContractVersion(smartContract.getVersion()); storage.generateAddrHash(smartContract.getTrxHash().toByteArray()); @@ -1177,7 +1212,8 @@ private TransactionJson buildCreateSmartContractTransaction(byte[] ownerAddress, tx = setTransactionPermissionId(args.getPermissionId(), txBuilder.build()); TransactionJson transactionJson = new TransactionJson(); - transactionJson.setTransaction(JSON.parseObject(Util.printCreateTransaction(tx, false))); + transactionJson.setTransaction( + JSONObject.outboundParseObject(Util.printCreateTransaction(tx, false))); return transactionJson; } catch (JsonRpcInvalidParamsException e) { @@ -1244,7 +1280,7 @@ private TransactionJson buildTriggerSmartContractTransaction(byte[] ownerAddress String jsonString = Util.printTransaction(trxExtBuilder.build().getTransaction(), args.isVisible()); TransactionJson transactionJson = new TransactionJson(); - transactionJson.setTransaction(JSON.parseObject(jsonString)); + transactionJson.setTransaction(JSONObject.outboundParseObject(jsonString)); return transactionJson; } @@ -1260,8 +1296,8 @@ private TransactionJson createTransactionJson(GeneratedMessageV3.Builder buil tx = setTransactionExtraData(args.getExtraData(), tx, args.isVisible()); TransactionJson transactionJson = new TransactionJson(); - transactionJson - .setTransaction(JSON.parseObject(Util.printCreateTransaction(tx, args.isVisible()))); + transactionJson.setTransaction( + JSONObject.outboundParseObject(Util.printCreateTransaction(tx, args.isVisible()))); return transactionJson; } catch (ContractValidateException e) { @@ -1613,7 +1649,17 @@ public Object[] getFilterResult(String filterId, Map ./logs/tron-%d{yyyy-MM-dd}.%i.log.gz - + 500MB 7 50GB diff --git a/framework/src/test/java/org/tron/common/BaseMethodTest.java b/framework/src/test/java/org/tron/common/BaseMethodTest.java index 9ee1dfa3b36..c91310681a1 100644 --- a/framework/src/test/java/org/tron/common/BaseMethodTest.java +++ b/framework/src/test/java/org/tron/common/BaseMethodTest.java @@ -10,6 +10,7 @@ import org.tron.common.application.Application; import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.PeerManagerStateResetter; import org.tron.core.ChainBaseManager; import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @@ -42,6 +43,9 @@ public abstract class BaseMethodTest { @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @Rule + public final VMConfigRule vmConfigRule = new VMConfigRule(); + protected TronApplicationContext context; protected Application appT; protected Manager dbManager; @@ -57,6 +61,7 @@ protected String configFile() { @Before public final void initContext() throws IOException { + PeerManagerStateResetter.reset(); String[] baseArgs = new String[]{ "--output-directory", temporaryFolder.newFolder().toString()}; String[] allArgs = mergeArgs(baseArgs, extraArgs()); diff --git a/framework/src/test/java/org/tron/common/BaseTest.java b/framework/src/test/java/org/tron/common/BaseTest.java index 6d075a2d6aa..471aaa3d383 100644 --- a/framework/src/test/java/org/tron/common/BaseTest.java +++ b/framework/src/test/java/org/tron/common/BaseTest.java @@ -7,7 +7,9 @@ import lombok.extern.slf4j.Slf4j; import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.ClassRule; +import org.junit.Rule; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.springframework.test.annotation.DirtiesContext; @@ -17,6 +19,7 @@ import org.tron.common.crypto.ECKey; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Commons; +import org.tron.common.utils.PeerManagerStateResetter; import org.tron.common.utils.Sha256Hash; import org.tron.consensus.base.Param; import org.tron.core.ChainBaseManager; @@ -64,6 +67,9 @@ public abstract class BaseTest { @ClassRule public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @Rule + public final VMConfigRule vmConfigRule = new VMConfigRule(); + @Resource protected Manager dbManager; @Resource @@ -75,6 +81,11 @@ public abstract class BaseTest { private static Application appT1; + @Before + public void resetPeerManagerState() { + PeerManagerStateResetter.reset(); + } + @PostConstruct private void prepare() { appT1 = appT; diff --git a/framework/src/test/java/org/tron/common/ParameterTest.java b/framework/src/test/java/org/tron/common/ParameterTest.java index 0b66c96462c..250738c127a 100644 --- a/framework/src/test/java/org/tron/common/ParameterTest.java +++ b/framework/src/test/java/org/tron/common/ParameterTest.java @@ -168,8 +168,6 @@ public void testCommonParameter() { assertEquals(1, parameter.getForbidTransferToContract()); parameter.setTrustNodeAddr("address"); assertEquals("address", parameter.getTrustNodeAddr()); - parameter.setWalletExtensionApi(false); - assertFalse(parameter.isWalletExtensionApi()); parameter.setEstimateEnergy(false); assertFalse(parameter.isEstimateEnergy()); parameter.setEstimateEnergyMaxRetry(2); diff --git a/framework/src/test/java/org/tron/common/VMConfigRule.java b/framework/src/test/java/org/tron/common/VMConfigRule.java new file mode 100644 index 00000000000..2ee7374d816 --- /dev/null +++ b/framework/src/test/java/org/tron/common/VMConfigRule.java @@ -0,0 +1,52 @@ +package org.tron.common; + +import java.lang.reflect.Field; +import org.junit.rules.ExternalResource; +import org.tron.common.parameter.CommonParameter; +import org.tron.core.vm.config.ConfigLoader; +import org.tron.core.vm.config.VMConfig; + +/** + * Restores VM flags after each test, including failed setup and assertion paths. + * + *

    Snapshotting enumerates {@link VMConfig.Snapshot} fields reflectively, so any static flag + * not mirrored there is outside this rule's protection: when adding a static flag to + * {@link VMConfig} or {@link ConfigLoader}, it must also be mirrored into + * {@code VMConfig.Snapshot} (before/after save and restore) or it will leak across tests. + * + *

    This is a method-level rule: the baseline is captured before every test method, so global + * flags written from class-level {@code @BeforeClass} code are not covered — such classes must + * add their own {@code @AfterClass} to reset them manually (a leaked London hard-fork flag from + * class-level setup is an instance of exactly this gap). + */ +public class VMConfigRule extends ExternalResource { + + private VMConfig.Snapshot savedSnapshot; + private boolean savedLoaderDisabled; + private boolean savedHardFork; + private boolean savedTrace; + + @Override + protected void before() throws Exception { + Field global = VMConfig.class.getDeclaredField("globalSnapshot"); + global.setAccessible(true); + VMConfig.Snapshot current = (VMConfig.Snapshot) global.get(null); + savedSnapshot = new VMConfig.Snapshot(); + // init* methods mutate the snapshot in place, so saving only its reference is insufficient. + for (Field flag : VMConfig.Snapshot.class.getFields()) { + flag.set(savedSnapshot, flag.get(current)); + } + savedLoaderDisabled = ConfigLoader.disable; + savedHardFork = CommonParameter.ENERGY_LIMIT_HARD_FORK; + savedTrace = VMConfig.vmTrace(); + VMConfig.clearLocalSnapshot(); + } + + @Override + protected void after() { + VMConfig.setGlobalSnapshot(savedSnapshot); + ConfigLoader.disable = savedLoaderDisabled; + VMConfig.initVmHardFork(savedHardFork); + VMConfig.setVmTrace(savedTrace); + } +} diff --git a/framework/src/test/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiterTest.java b/framework/src/test/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiterTest.java deleted file mode 100644 index fc578ca7947..00000000000 --- a/framework/src/test/java/org/tron/common/application/GrpcNettyMaxConcurrentStreamsLimiterTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * java-tron is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * java-tron is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with java-tron. If not, see . - */ - -package org.tron.common.application; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; - -import io.grpc.ChannelLogger; -import io.grpc.ChannelLogger.ChannelLogLevel; -import io.grpc.netty.GrpcHttp2ConnectionHandler; -import io.grpc.netty.InternalProtocolNegotiator; -import io.netty.channel.ChannelHandler; -import io.netty.handler.codec.http2.DefaultHttp2Connection; -import io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder; -import io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder; -import io.netty.handler.codec.http2.DefaultHttp2FrameReader; -import io.netty.handler.codec.http2.DefaultHttp2FrameWriter; -import io.netty.handler.codec.http2.Http2Connection; -import io.netty.handler.codec.http2.Http2ConnectionDecoder; -import io.netty.handler.codec.http2.Http2ConnectionEncoder; -import io.netty.handler.codec.http2.Http2Error; -import io.netty.handler.codec.http2.Http2Exception; -import io.netty.handler.codec.http2.Http2FrameWriter; -import io.netty.handler.codec.http2.Http2Settings; -import org.junit.Test; - -public class GrpcNettyMaxConcurrentStreamsLimiterTest { - - private static final ChannelLogger NOOP_LOGGER = new ChannelLogger() { - @Override - public void log(ChannelLogLevel level, String message) { - } - - @Override - public void log(ChannelLogLevel level, String messageFormat, Object... args) { - } - }; - - @Test - public void shouldEnforceMaxStreamsBeforeSettingsAck() throws Exception { - Http2Connection connection = new DefaultHttp2Connection(true); - GrpcHttp2ConnectionHandler grpcHandler = newGrpcHandler(connection); - InternalProtocolNegotiator.ProtocolNegotiator negotiator = - GrpcNettyMaxConcurrentStreamsLimiter.newPlaintextNegotiator(2); - - ChannelHandler negotiationHandler = negotiator.newHandler(grpcHandler); - - assertNotNull(negotiationHandler); - assertEquals(2, connection.remote().maxActiveStreams()); - connection.remote().createStream(1, true); - connection.remote().createStream(3, true); - Http2Exception exception = assertThrows( - Http2Exception.class, () -> connection.remote().createStream(5, true)); - assertEquals(Http2Error.REFUSED_STREAM, exception.error()); - negotiator.close(); - } - - @Test - public void shouldIgnoreClientMaxHeaderListSizeOnServer() throws Exception { - Http2Connection connection = new DefaultHttp2Connection(true); - Http2FrameWriter frameWriter = new DefaultHttp2FrameWriter(); - Http2ConnectionEncoder encoder = - new DefaultHttp2ConnectionEncoder(connection, frameWriter); - long originalMaxHeaderListSize = - encoder.configuration().headersConfiguration().maxHeaderListSize(); - - encoder.remoteSettings(new Http2Settings().maxHeaderListSize(1)); - - assertEquals(originalMaxHeaderListSize, - encoder.configuration().headersConfiguration().maxHeaderListSize()); - encoder.close(); - } - - @Test - public void shouldRejectNonPositiveStreamLimit() { - IllegalArgumentException zeroLimitException = assertThrows(IllegalArgumentException.class, - () -> GrpcNettyMaxConcurrentStreamsLimiter.newPlaintextNegotiator(0)); - assertEquals("maxConcurrentStreams must be positive", zeroLimitException.getMessage()); - IllegalArgumentException negativeLimitException = assertThrows(IllegalArgumentException.class, - () -> GrpcNettyMaxConcurrentStreamsLimiter.newPlaintextNegotiator(-1)); - assertEquals("maxConcurrentStreams must be positive", negativeLimitException.getMessage()); - } - - private static GrpcHttp2ConnectionHandler newGrpcHandler(Http2Connection connection) { - Http2FrameWriter frameWriter = new DefaultHttp2FrameWriter(); - Http2ConnectionEncoder encoder = - new DefaultHttp2ConnectionEncoder(connection, frameWriter); - Http2ConnectionDecoder decoder = new DefaultHttp2ConnectionDecoder( - connection, encoder, new DefaultHttp2FrameReader()); - return new GrpcHttp2ConnectionHandler( - null, decoder, encoder, new Http2Settings(), NOOP_LOGGER) { - }; - } -} diff --git a/framework/src/test/java/org/tron/common/application/NettyHttp2HeaderSecurityTest.java b/framework/src/test/java/org/tron/common/application/NettyHttp2HeaderSecurityTest.java new file mode 100644 index 00000000000..6a4f4330f04 --- /dev/null +++ b/framework/src/test/java/org/tron/common/application/NettyHttp2HeaderSecurityTest.java @@ -0,0 +1,53 @@ +/* + * java-tron is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * java-tron is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with java-tron. If not, see . + */ + +package org.tron.common.application; + +import static org.junit.Assert.assertEquals; + +import io.netty.handler.codec.http2.DefaultHttp2Connection; +import io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder; +import io.netty.handler.codec.http2.DefaultHttp2FrameWriter; +import io.netty.handler.codec.http2.Http2Connection; +import io.netty.handler.codec.http2.Http2ConnectionEncoder; +import io.netty.handler.codec.http2.Http2FrameWriter; +import io.netty.handler.codec.http2.Http2Settings; +import org.junit.Test; + +/** Guards the netty HTTP/2 header-size behaviour the gRPC server relies on. */ +public class NettyHttp2HeaderSecurityTest { + + /** + * CVE-2026-50560: SETTINGS_MAX_HEADER_LIST_SIZE tells the server what the client is willing to + * receive, so it must not shrink the server encoder's own limit. Otherwise a hostile client can + * advertise a tiny value and make every response-header write throw, which is a Rapid-Reset-like + * denial of service. Netty enforced the client value before 4.1.135.Final / 4.2.15.Final. + */ + @Test + public void shouldIgnoreClientMaxHeaderListSizeOnServer() throws Exception { + Http2Connection connection = new DefaultHttp2Connection(true); + Http2FrameWriter frameWriter = new DefaultHttp2FrameWriter(); + Http2ConnectionEncoder encoder = + new DefaultHttp2ConnectionEncoder(connection, frameWriter); + long originalMaxHeaderListSize = + encoder.configuration().headersConfiguration().maxHeaderListSize(); + + encoder.remoteSettings(new Http2Settings().maxHeaderListSize(1)); + + assertEquals(originalMaxHeaderListSize, + encoder.configuration().headersConfiguration().maxHeaderListSize()); + encoder.close(); + } +} diff --git a/framework/src/test/java/org/tron/common/backup/BackupManagerTest.java b/framework/src/test/java/org/tron/common/backup/BackupManagerTest.java index 5ff02fc8cb5..0efbb13a481 100644 --- a/framework/src/test/java/org/tron/common/backup/BackupManagerTest.java +++ b/framework/src/test/java/org/tron/common/backup/BackupManagerTest.java @@ -1,5 +1,6 @@ package org.tron.common.backup; +import io.netty.channel.Channel; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.InetAddress; @@ -9,8 +10,8 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import org.junit.After; import org.junit.Assert; @@ -25,6 +26,7 @@ import org.tron.common.backup.socket.UdpEvent; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.ReflectUtils; import org.tron.core.config.args.Args; import org.tron.core.config.args.InetUtil; @@ -34,7 +36,8 @@ public class BackupManagerTest { public TemporaryFolder temporaryFolder = new TemporaryFolder(); private BackupManager manager; private BackupServer backupServer; - private BiFunction savedLookup; + private BiFunction previousDnsLookup; + private boolean backupServerClosed; @Before public void setUp() throws Exception { @@ -43,13 +46,36 @@ public void setUp() throws Exception { CommonParameter.getInstance().setBackupPort(PublicMethod.chooseRandomPort()); manager = new BackupManager(); backupServer = new BackupServer(manager); - savedLookup = InetUtil.dnsLookup; + previousDnsLookup = InetUtil.dnsLookup; } @After - public void tearDown() { - InetUtil.dnsLookup = savedLookup; + public void tearDown() throws Exception { + List errors = new ArrayList<>(); + Channel channel = null; + if (backupServer != null) { + try { + channel = BackupTestUtils.getChannel(backupServer); + } catch (Throwable t) { + errors.add(t); + } + } + if (!backupServerClosed && backupServer != null) { + BackupTestUtils.runQuietly(errors, backupServer::close); + } + if (manager != null) { + BackupTestUtils.runQuietly(errors, manager::stop); + } + Channel captured = channel; + BackupTestUtils.runQuietly(errors, () -> { + if (captured != null) { + Assert.assertFalse("backup channel must close", captured.isOpen()); + } + BackupTestUtils.assertExecutorsTerminated(manager, backupServer); + }); + InetUtil.dnsLookup = previousDnsLookup; Args.clearParam(); + BackupTestUtils.throwIfAnyError(errors); } @Test @@ -121,7 +147,7 @@ public void test() throws Exception { } @Test - public void testSendKeepAliveMessage() throws Exception { + public void testBackupServerLifecycleDuringKeepAliveInterval() throws Exception { CommonParameter parameter = CommonParameter.getInstance(); parameter.setBackupPriority(8); List members = new ArrayList<>(); @@ -134,21 +160,19 @@ public void testSendKeepAliveMessage() throws Exception { Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.MASTER); backupServer.initServer(); + awaitBackupServerReady(); manager.init(); - - Thread.sleep(parameter.getKeepAliveInterval() + 1000);//test send KeepAliveMessage - - field = manager.getClass().getDeclaredField("executorService"); - field.setAccessible(true); - ScheduledExecutorService executorService = (ScheduledExecutorService) field.get(manager); - executorService.shutdown(); - - Field field2 = backupServer.getClass().getDeclaredField("executor"); - field2.setAccessible(true); - ExecutorService executorService2 = (ExecutorService) field2.get(backupServer); - executorService2.shutdown(); + long keepAliveDeadline = System.nanoTime() + + TimeUnit.MILLISECONDS.toNanos(parameter.getKeepAliveInterval() + 1000L); + BackupTestUtils.awaitCondition("keep-alive interval", + () -> System.nanoTime() >= keepAliveDeadline); Assert.assertEquals(BackupManager.BackupStatusEnum.INIT, manager.getStatus()); + Channel channel = BackupTestUtils.getChannel(backupServer); + backupServer.close(); + backupServerClosed = true; + Assert.assertFalse("backup channel must close", channel.isOpen()); + BackupTestUtils.assertExecutorsTerminated(manager, backupServer); } // ===== domain-handling tests for init() ===== @@ -161,8 +185,8 @@ public void testInitResolvesDomainsToMembers() throws Exception { InetUtil.dnsLookup = (host, ipv4) -> ("node.example.com".equals(host) && ipv4) ? resolved : null; manager.init(); - Set members = getField(manager, "members"); - Map cache = getField(manager, "domainIpCache"); + Set members = ReflectUtils.getFieldValue(manager, "members"); + Map cache = ReflectUtils.getFieldValue(manager, "domainIpCache"); Assert.assertTrue(members.contains("1.2.3.4")); Assert.assertEquals("1.2.3.4", cache.get("node.example.com")); manager.stop(); @@ -174,8 +198,8 @@ public void testInitSkipsUnresolvableDomain() throws Exception { Collections.singletonList("bad.invalid.domain")); InetUtil.dnsLookup = (host, ipv4) -> null; manager.init(); - Set members = getField(manager, "members"); - Map cache = getField(manager, "domainIpCache"); + Set members = ReflectUtils.getFieldValue(manager, "members"); + Map cache = ReflectUtils.getFieldValue(manager, "domainIpCache"); Assert.assertTrue("unresolvable domain should be silently dropped", members.isEmpty()); Assert.assertTrue(cache.isEmpty()); manager.stop(); @@ -190,7 +214,7 @@ public void testInitSkipsDomainResolvingToLocalIp() throws Exception { InetUtil.dnsLookup = (host, ipv4) -> ("self.local.host".equals(host) && ipv4) ? selfAddr : null; manager.init(); - Set members = getField(manager, "members"); + Set members = ReflectUtils.getFieldValue(manager, "members"); Assert.assertFalse("domain resolving to local IP should not be in members", members.contains(localIp)); manager.stop(); @@ -200,8 +224,8 @@ public void testInitSkipsDomainResolvingToLocalIp() throws Exception { @Test(timeout = 5000) public void testRefreshMemberIpsIpChanged() throws Exception { - Set members = getField(manager, "members"); - Map cache = getField(manager, "domainIpCache"); + Set members = ReflectUtils.getFieldValue(manager, "members"); + Map cache = ReflectUtils.getFieldValue(manager, "domainIpCache"); members.add("1.1.1.1"); cache.put("peer.tron.network", "1.1.1.1"); @@ -216,8 +240,8 @@ public void testRefreshMemberIpsIpChanged() throws Exception { @Test(timeout = 5000) public void testRefreshMemberIpsIpUnchanged() throws Exception { - Set members = getField(manager, "members"); - Map cache = getField(manager, "domainIpCache"); + Set members = ReflectUtils.getFieldValue(manager, "members"); + Map cache = ReflectUtils.getFieldValue(manager, "domainIpCache"); members.add("1.1.1.1"); cache.put("peer.tron.network", "1.1.1.1"); @@ -231,8 +255,8 @@ public void testRefreshMemberIpsIpUnchanged() throws Exception { @Test(timeout = 5000) public void testRefreshMemberIpsDnsFailure() throws Exception { - Set members = getField(manager, "members"); - Map cache = getField(manager, "domainIpCache"); + Set members = ReflectUtils.getFieldValue(manager, "members"); + Map cache = ReflectUtils.getFieldValue(manager, "domainIpCache"); members.add("1.1.1.1"); cache.put("peer.tron.network", "1.1.1.1"); @@ -242,16 +266,18 @@ public void testRefreshMemberIpsDnsFailure() throws Exception { Assert.assertEquals("1.1.1.1", cache.get("peer.tron.network")); } - @SuppressWarnings("unchecked") - private T getField(Object obj, String name) throws Exception { - Field f = obj.getClass().getDeclaredField(name); - f.setAccessible(true); - return (T) f.get(obj); - } - private void invokeRefreshMemberIps(BackupManager mgr) throws Exception { Method m = mgr.getClass().getDeclaredMethod("refreshMemberIps"); m.setAccessible(true); m.invoke(mgr); } + + private void awaitBackupServerReady() throws Exception { + BackupTestUtils.awaitCondition("backup channel to become active", + () -> BackupTestUtils.getChannel(backupServer) != null + && BackupTestUtils.getChannel(backupServer).isActive()); + BackupTestUtils.awaitCondition("backup message handler assignment", + () -> ReflectUtils.getFieldObject(manager, "messageHandler") != null); + } + } diff --git a/framework/src/test/java/org/tron/common/backup/BackupServerTest.java b/framework/src/test/java/org/tron/common/backup/BackupServerTest.java index 50778970d87..b1d60d5d38b 100644 --- a/framework/src/test/java/org/tron/common/backup/BackupServerTest.java +++ b/framework/src/test/java/org/tron/common/backup/BackupServerTest.java @@ -1,8 +1,10 @@ package org.tron.common.backup; +import io.netty.channel.Channel; import java.util.ArrayList; import java.util.List; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -23,6 +25,8 @@ public class BackupServerTest { @Rule public Timeout globalTimeout = Timeout.seconds(60); private BackupServer backupServer; + private BackupManager backupManager; + private boolean backupServerClosed; @Before public void setUp() throws Exception { @@ -32,21 +36,39 @@ public void setUp() throws Exception { List members = new ArrayList<>(); members.add("127.0.0.2"); CommonParameter.getInstance().setBackupMembers(members); - BackupManager backupManager = new BackupManager(); + backupManager = new BackupManager(); backupManager.init(); backupServer = new BackupServer(backupManager); } @After - public void tearDown() { - backupServer.close(); + public void tearDown() throws Exception { + List errors = new ArrayList<>(); + if (!backupServerClosed && backupServer != null) { + BackupTestUtils.runQuietly(errors, backupServer::close); + } + if (backupManager != null) { + BackupTestUtils.runQuietly(errors, backupManager::stop); + } + BackupTestUtils.runQuietly(errors, + () -> BackupTestUtils.assertExecutorsTerminated(backupManager, backupServer)); Args.clearParam(); + BackupTestUtils.throwIfAnyError(errors); } @Test(timeout = 60_000) - public void test() throws InterruptedException { + public void test() throws Exception { backupServer.initServer(); - // wait for the server to start so channel is assigned before close() is called - Thread.sleep(1000); + BackupTestUtils.awaitCondition("backup channel to become active", + () -> BackupTestUtils.getChannel(backupServer) != null + && BackupTestUtils.getChannel(backupServer).isActive()); + Channel channel = BackupTestUtils.getChannel(backupServer); + Assert.assertTrue("backup channel must be active after startup", channel.isActive()); + + backupServer.close(); + backupServerClosed = true; + + Assert.assertFalse("backup channel must close", channel.isOpen()); + BackupTestUtils.assertExecutorsTerminated(backupManager, backupServer); } } diff --git a/framework/src/test/java/org/tron/common/backup/BackupTestUtils.java b/framework/src/test/java/org/tron/common/backup/BackupTestUtils.java new file mode 100644 index 00000000000..45f2cae596f --- /dev/null +++ b/framework/src/test/java/org/tron/common/backup/BackupTestUtils.java @@ -0,0 +1,72 @@ +package org.tron.common.backup; + +import io.netty.channel.Channel; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; +import org.junit.Assert; +import org.junit.function.ThrowingRunnable; +import org.tron.common.backup.socket.BackupServer; +import org.tron.common.utils.ReflectUtils; + +/** + * Shared reflection/await/cleanup helpers for backup tests. Assertion messages and timeout + * parameters mirror the helpers they replace, so failure output is unchanged. + */ +public final class BackupTestUtils { + + private BackupTestUtils() { + } + + public static Channel getChannel(BackupServer server) { + try { + return (Channel) ReflectUtils.getFieldObject(server, "channel"); + } catch (Exception e) { + throw new AssertionError("cannot inspect backup channel", e); + } + } + + public static void awaitCondition(String description, BooleanSupplier condition) + throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + if (condition.getAsBoolean()) { + return; + } + Thread.sleep(20); + } + Assert.fail("timed out waiting for " + description); + } + + public static void assertExecutorsTerminated(BackupManager manager, BackupServer server) + throws Exception { + if (manager == null || server == null) { + return; + } + ExecutorService managerExecutor = + (ExecutorService) ReflectUtils.getFieldObject(manager, "executorService"); + Assert.assertTrue("backup manager executor must terminate", managerExecutor.isTerminated()); + ExecutorService serverExecutor = + (ExecutorService) ReflectUtils.getFieldObject(server, "executor"); + if (serverExecutor != null) { + Assert.assertTrue("backup server executor must terminate", serverExecutor.isTerminated()); + } + } + + public static void runQuietly(List errors, ThrowingRunnable step) { + try { + step.run(); + } catch (Throwable t) { + errors.add(t); + } + } + + public static void throwIfAnyError(List errors) { + if (!errors.isEmpty()) { + AssertionError failure = new AssertionError("backup test cleanup failed"); + errors.forEach(failure::addSuppressed); + throw failure; + } + } +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java b/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java index 958af4f7b7b..0857b1b9391 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java @@ -15,6 +15,7 @@ import org.pf4j.PluginWrapper; import org.tron.common.logsfilter.trigger.BlockLogTrigger; import org.tron.common.logsfilter.trigger.TransactionLogTrigger; +import org.tron.common.utils.PublicMethod; public class EventLoaderTest { @@ -22,7 +23,7 @@ public class EventLoaderTest { public void launchNativeQueue() { EventPluginConfig config = new EventPluginConfig(); config.setSendQueueLength(1000); - config.setBindPort(5555); + config.setBindPort(PublicMethod.chooseRandomPort()); config.setUseNativeQueue(true); config.setPluginPath("pluginPath"); config.setServerAddress("serverAddress"); @@ -48,9 +49,11 @@ public void launchNativeQueue() { config.setTriggerConfigList(triggerConfigList); - assertTrue(EventPluginLoader.getInstance().start(config)); - - EventPluginLoader.getInstance().stopPlugin(); + try { + assertTrue(EventPluginLoader.getInstance().start(config)); + } finally { + EventPluginLoader.getInstance().stopPlugin(); + } } @Test diff --git a/framework/src/test/java/org/tron/common/logsfilter/NativeMessageQueueTest.java b/framework/src/test/java/org/tron/common/logsfilter/NativeMessageQueueTest.java index 5219654977b..b32f1c22d39 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/NativeMessageQueueTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/NativeMessageQueueTest.java @@ -6,13 +6,16 @@ import org.junit.Test; import org.tron.common.es.ExecutorServiceManager; import org.tron.common.logsfilter.nativequeue.NativeMessageQueue; +import org.tron.common.utils.PublicMethod; import org.zeromq.SocketType; import org.zeromq.ZContext; import org.zeromq.ZMQ; public class NativeMessageQueueTest { - public int bindPort = 5555; + // Random port avoids fixed 5555 conflicts; note invalidBindPort/invalidSendLength still + // remap to DEFAULT_BIND_PORT (5555) in production start() — known low-risk residual. + public int bindPort = PublicMethod.chooseRandomPort(); public String dataToSend = "################"; public String topic = "testTopic"; diff --git a/framework/src/test/java/org/tron/common/prometheus/SRMetricsTest.java b/framework/src/test/java/org/tron/common/prometheus/SRMetricsTest.java index 4c2e9292d29..4c1404bb232 100644 --- a/framework/src/test/java/org/tron/common/prometheus/SRMetricsTest.java +++ b/framework/src/test/java/org/tron/common/prometheus/SRMetricsTest.java @@ -13,6 +13,7 @@ import org.junit.Test; import org.tron.common.BaseTest; import org.tron.common.TestConstants; +import org.tron.common.utils.PublicMethod; import org.tron.common.utils.StringUtil; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.core.capsule.AccountCapsule; @@ -38,6 +39,7 @@ public class SRMetricsTest extends BaseTest { Args.setParam(new String[]{"-d", dbPath()}, TestConstants.TEST_CONF); Args.getInstance().setNodeListenPort(20000 + PORT.incrementAndGet()); Args.getInstance().setMetricsPrometheusEnable(true); + Args.getInstance().setMetricsPrometheusPort(PublicMethod.chooseRandomPort()); Metrics.init(); } diff --git a/framework/src/test/java/org/tron/common/runtime/VMActuatorMockTest.java b/framework/src/test/java/org/tron/common/runtime/VMActuatorMockTest.java index ab147f57a79..013ba606e9a 100644 --- a/framework/src/test/java/org/tron/common/runtime/VMActuatorMockTest.java +++ b/framework/src/test/java/org/tron/common/runtime/VMActuatorMockTest.java @@ -1,6 +1,8 @@ package org.tron.common.runtime; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.same; import java.lang.reflect.Field; import java.util.Collections; @@ -13,19 +15,70 @@ import org.tron.common.runtime.vm.LogInfo; import org.tron.core.actuator.VMActuator; import org.tron.core.db.TransactionContext; +import org.tron.core.vm.JumpTable; import org.tron.core.vm.OperationRegistry; import org.tron.core.vm.VM; import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.program.Program; +import org.tron.core.vm.repository.Repository; public class VMActuatorMockTest { @BeforeClass public static void init() { - // warm up the registry so VM.play(..., OperationRegistry.getTable()) arg eval is safe + // Warm up the registry before VM execution timing starts. OperationRegistry.init(); } + @Test + public void constantCallUsesDedicatedJumpTable() throws Exception { + try (MockedStatic vmMock = Mockito.mockStatic(VM.class)) { + Program program = Mockito.mock(Program.class); + Mockito.when(program.getResult()).thenReturn(new ProgramResult()); + + VMActuator actuator = new VMActuator(true); + Field f = VMActuator.class.getDeclaredField("program"); + f.setAccessible(true); + f.set(actuator, program); + + TransactionContext context = Mockito.mock(TransactionContext.class); + Mockito.when(context.getProgramResult()).thenReturn(new ProgramResult()); + + actuator.execute(context); + + JumpTable transactionTable = OperationRegistry.getTable(false); + JumpTable constantCallTable = OperationRegistry.getTable(true); + vmMock.verify(() -> VM.play(any(), same(constantCallTable))); + vmMock.verify(() -> VM.play(any(), argThat(table -> table != transactionTable))); + } + } + + @Test + public void nonConstantCallUsesSharedJumpTable() throws Exception { + try (MockedStatic vmMock = Mockito.mockStatic(VM.class)) { + Program program = Mockito.mock(Program.class); + Mockito.when(program.getResult()).thenReturn(new ProgramResult()); + + VMActuator actuator = new VMActuator(false); + Field f = VMActuator.class.getDeclaredField("program"); + f.setAccessible(true); + f.set(actuator, program); + + Field repositoryField = VMActuator.class.getDeclaredField("rootRepository"); + repositoryField.setAccessible(true); + repositoryField.set(actuator, Mockito.mock(Repository.class)); + + TransactionContext context = Mockito.mock(TransactionContext.class); + Mockito.when(context.getProgramResult()).thenReturn(new ProgramResult()); + + actuator.execute(context); + + // The non-constant call must receive the shared consensus table itself. + JumpTable shared = OperationRegistry.getTable(false); + vmMock.verify(() -> VM.play(any(), same(shared))); + } + } + private void runCatchPathTest(Throwable thrownByVm, boolean osakaOn, int expectedSize) throws Exception { boolean prevOsaka = VMConfig.allowTvmOsaka(); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmCompatibleEvmTest.java b/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmCompatibleEvmTest.java index 74d44dfca7d..a3711ba8de7 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmCompatibleEvmTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmCompatibleEvmTest.java @@ -306,6 +306,7 @@ public static void afterClass() { VMConfig.initAllowTvmConstantinople(0); VMConfig.initAllowTvmSolidity059(0); VMConfig.initAllowTvmIstanbul(0); + VMConfig.initAllowTvmLondon(0); VMConfig.initAllowTvmCompatibleEvm(0); } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmLondonTest.java b/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmLondonTest.java index e93eca39092..11a02e615db 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmLondonTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmLondonTest.java @@ -74,8 +74,8 @@ public void testBaseFee() throws ContractExeException, ReceiptCheckErrException, factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); byte[] returnValue = result.getRuntime().getResult().getHReturn(); Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertArrayEquals(returnValue, - longTo32Bytes(manager.getDynamicPropertiesStore().getEnergyFee())); + Assert.assertArrayEquals(longTo32Bytes(manager.getDynamicPropertiesStore().getEnergyFee()), + returnValue); } @Test diff --git a/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java b/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java index 5a58407f887..6fa2801c51f 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java @@ -209,8 +209,7 @@ private void testJsonRpc(byte[] actualContract, long loop) { NodeInfoService nodeInfoService; nodeInfoService = context.getBean(NodeInfoService.class); Wallet wallet = context.getBean(Wallet.class); - tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet); - tronJsonRpc.setManager(manager); + tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, manager); try { String res = tronJsonRpc.getStorageAt(ByteArray.toHexString(actualContract), "0", "latest"); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java b/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java index a1627f4f2e2..d6c344263dd 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java @@ -3,6 +3,7 @@ import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.tron.core.config.Parameter.ChainConstant.FROZEN_PERIOD; +import static org.tron.core.config.Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2; import java.util.List; import java.util.Locale; @@ -16,6 +17,7 @@ import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; +import org.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; @@ -24,6 +26,7 @@ import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.InternalTransaction; import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.ForkController; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; @@ -42,6 +45,7 @@ import org.tron.core.vm.config.ConfigLoader; import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.program.Program; +import org.tron.core.vm.program.Program.OutOfTimeException; import org.tron.core.vm.program.invoke.ProgramInvokeMockImpl; import org.tron.core.vm.repository.Repository; import org.tron.protos.Protocol; @@ -51,7 +55,7 @@ public class OperationsTest extends BaseTest { private ProgramInvokeMockImpl invoke; private Program program; - private final JumpTable jumpTable = OperationRegistry.getTable(); + private final JumpTable jumpTable = OperationRegistry.prepareAndGetTable(false); @Autowired private Wallet wallet; @@ -1182,6 +1186,7 @@ public void testSuicideAction() throws ContractValidateException { program.suicide(new DataWord( dbManager.getAccountStore().getBlackhole().getAddress().toByteArray())); + Assert.assertTrue(program.getContractState().isSelfDestructed(program.getContextAddress())); DecodeUtil.addressPreFixByte = prePrefixByte; VMConfig.initAllowEnergyAdjustment(0); @@ -1240,6 +1245,7 @@ public void testSuicideAction2() throws ContractValidateException { OperationActions.suicideAction2(program); Assert.assertEquals(1, program.getResult().getDeleteAccounts().size()); + Assert.assertTrue(program.getContractState().isSelfDestructed(contractAddr)); invoke = new ProgramInvokeMockImpl(StoreFactory.getInstance(), new byte[0], contractAddr); @@ -1256,6 +1262,7 @@ public void testSuicideAction2() throws ContractValidateException { dbManager.getAccountStore().getBlackhole().getAddress().toByteArray())); Assert.assertEquals(0, spyProgram.getResult().getDeleteAccounts().size()); + Assert.assertTrue(spyProgram.getContractState().isSelfDestructed(contractAddr)); DecodeUtil.addressPreFixByte = prePrefixByte; VMConfig.initAllowEnergyAdjustment(0); @@ -1266,6 +1273,31 @@ public void testSuicideAction2() throws ContractValidateException { VMConfig.initAllowTvmVote(0); } + @Test + public void testSuicide2RejectsSelfDestructedBeneficiaryAfterFork() + throws ContractValidateException { + byte[] contractAddr = Hex.decode("41471fd3ad3e9eeadeec4608b92d16ce6b500704cc"); + byte[] beneficiary = Hex.decode("411111111111111111111111111111111111111111"); + invoke = new ProgramInvokeMockImpl(StoreFactory.getInstance(), new byte[0], contractAddr); + program = new Program(null, null, invoke, + new InternalTransaction( + Protocol.Transaction.getDefaultInstance(), + InternalTransaction.TrxType.TRX_UNKNOWN_TYPE)); + program.getContractState().markSelfDestruct(beneficiary); + + ForkController forkController = Mockito.mock(ForkController.class); + try (MockedStatic fork = Mockito.mockStatic(ForkController.class)) { + fork.when(ForkController::instance).thenReturn(forkController); + Mockito.when(forkController.pass(VERSION_4_8_2_2)).thenReturn(true); + + OutOfTimeException exception = Assert.assertThrows(OutOfTimeException.class, + () -> program.suicide2(new DataWord(beneficiary))); + Assert.assertEquals( + "CPU timeout for SELFDESTRUCT with selfdestructed beneficiary", + exception.getMessage()); + } + } + @Test public void testVoteWitnessCost() throws ContractValidateException { // Build stack environment, the stack from top to bottom is 0x00, 0x80, 0x00, 0x80 diff --git a/framework/src/test/java/org/tron/common/runtime/vm/OptimizeTvmStorageTest.java b/framework/src/test/java/org/tron/common/runtime/vm/OptimizeTvmStorageTest.java new file mode 100644 index 00000000000..c0120059b84 --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/OptimizeTvmStorageTest.java @@ -0,0 +1,261 @@ +package org.tron.common.runtime.vm; + +import static org.tron.protos.Protocol.Transaction.Result.contractResult.OUT_OF_TIME; +import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS; + +import java.util.Arrays; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.crypto.Hash; +import org.tron.common.runtime.Runtime; +import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.ByteUtil; +import org.tron.common.utils.ForkController; +import org.tron.core.capsule.StorageRowCapsule; +import org.tron.core.config.Parameter.ForkBlockVersionEnum; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.program.Program.OutOfTimeException; +import org.tron.core.vm.repository.RepositoryImpl; +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.Protocol.Transaction; + +public class OptimizeTvmStorageTest extends VMTestBase { + + private static final long FEE_LIMIT = 1_000_000_000L; + private static final String NON_ALIAS = + "6001600155600260025500"; + private static final String ALIAS = + "600160015560027f00000000000000000000000000000001000000000000000000000000000000015500"; + + @Override + protected void beforeDestroy() { + VMConfig.initAllowOptimizeTvmStorage(0); + } + + @Test + public void optimizedKeyKeepsFullSlotAndTombstone() { + activateFork(); + VMConfig.initAllowOptimizeTvmStorage(1); + byte[] address = account("00000000000000000000000000000000000000c1"); + rootRepository.createAccount(address, AccountType.Normal); + rootRepository.addBalance(address, 1_000_000L); + + byte[] slotA = word(1); + byte[] slotB = word(1); + slotB[15] = 1; + rootRepository.putStorageValue(address, new DataWord(slotA), new DataWord(5)); + rootRepository.putStorageValue(address, new DataWord(slotA), new DataWord(0)); + rootRepository.commit(); + rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + rootRepository.putStorageValue(address, new DataWord(slotB), new DataWord(6)); + rootRepository.commit(); + + byte[] newA = optimizedKey(address, slotA); + byte[] newB = optimizedKey(address, slotB); + Assert.assertEquals(48, newA.length); + Assert.assertFalse(Arrays.equals(newA, newB)); + byte[] storedA = dbManager.getStorageRowStore().get(newA).getValue(); + byte[] storedB = dbManager.getStorageRowStore().get(newB).getValue(); + Assert.assertEquals(32, storedA.length); + Assert.assertTrue(new DataWord(storedA).isZero()); + Assert.assertEquals(6L, new DataWord(storedB).longValue()); + + byte[] legacyOnly = word(2); + byte[] legacyKey = legacyKey(address, legacyOnly); + dbManager.getStorageRowStore().put(legacyKey, new StorageRowCapsule(new DataWord(7).getData())); + rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + DataWord loaded = rootRepository.getStorageValue(address, new DataWord(legacyOnly)); + Assert.assertEquals(7L, loaded.longValue()); + rootRepository.putStorageValue(address, new DataWord(legacyOnly), new DataWord(9)); + rootRepository.commit(); + byte[] migrated = dbManager.getStorageRowStore().get(optimizedKey(address, legacyOnly)) + .getValue(); + Assert.assertEquals(9L, new DataWord(migrated).longValue()); + Assert.assertFalse(dbManager.getStorageRowStore().has(legacyKey)); + DataWord after = RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, new DataWord(legacyOnly)); + Assert.assertEquals(9L, after.longValue()); + } + + @Test + public void migratedWriteClearsSharedLegacyRow() { + activateFork(); + VMConfig.initAllowOptimizeTvmStorage(1); + byte[] address = account("00000000000000000000000000000000000000c3"); + rootRepository.createAccount(address, AccountType.Normal); + rootRepository.commit(); + + byte[] slotA = word(1); + byte[] slotB = word(1); + slotB[15] = 1; + byte[] legacy = legacyKey(address, slotA); + Assert.assertArrayEquals(legacy, legacyKey(address, slotB)); + dbManager.getStorageRowStore().put(legacy, + new StorageRowCapsule(new DataWord(100).getData())); + + rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + rootRepository.putStorageValue(address, new DataWord(slotA), DataWord.ZERO()); + rootRepository.commit(); + + rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + Assert.assertNull(rootRepository.getStorageValue(address, new DataWord(slotB))); + Assert.assertFalse(dbManager.getStorageRowStore().has(legacy)); + Assert.assertNull(rootRepository.getStorageValue(address, new DataWord(slotA))); + byte[] stored = dbManager.getStorageRowStore() + .get(optimizedKey(address, slotA)).getValue(); + Assert.assertTrue(new DataWord(stored).isZero()); + } + + @Test + public void zeroThenNonZeroKeepsLegacyChargeBeforeProposal() throws Exception { + activateFork(); + long fresh = deploy("600160005500").getResult().getEnergyUsed(); + long zeroThenSet = deploy("6000600055600160005500").getResult().getEnergyUsed(); + // Proposal off: a cached 0 still counts as an existing value, so the second + // write is RESET (5000), not SET (20000). Delta against a fresh SET is + // two extra PUSH1 (6) + 5000 - 20000. + Assert.assertEquals(-9994L, zeroThenSet - fresh); + } + + @Test + public void zeroThenNonZeroKeepsResetChargeWhenOptimized() throws Exception { + activateFork(); + dbManager.getDynamicPropertiesStore().saveAllowOptimizeTvmStorage(1); + try { + long fresh = deploy("FreshSet", "600160005500").getResult().getEnergyUsed(); + long zeroThenSet = deploy("ZeroThenSet", "6000600055600160005500") + .getResult().getEnergyUsed(); + // A zero written earlier in this transaction stays in the cache, so the + // following non-zero write is RESET (5000), same as before the proposal. + Assert.assertEquals(-9994L, zeroThenSet - fresh); + } finally { + dbManager.getDynamicPropertiesStore().saveAllowOptimizeTvmStorage(0); + } + } + + @Test + public void tombstoneThenNonZeroChargesAsFirstWrite() throws Exception { + activateFork(); + dbManager.getDynamicPropertiesStore().saveAllowTvmConstantinople(1); + dbManager.getDynamicPropertiesStore().saveAllowOptimizeTvmStorage(1); + VMConfig.initAllowOptimizeTvmStorage(1); + try { + String init = "6006600c60003960066000f3600160005500"; + Runtime seededRuntime = deploy("Seeded", init); + Runtime freshRuntime = deploy("Fresh", init); + Assert.assertEquals(SUCCESS, seededRuntime.getResult().getResultCode()); + Assert.assertEquals(SUCCESS, freshRuntime.getResult().getResultCode()); + byte[] seeded = seededRuntime.getResult().getContractAddress(); + byte[] fresh = freshRuntime.getResult().getContractAddress(); + + RepositoryImpl repo = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repo.putStorageValue(seeded, new DataWord(0), DataWord.ZERO()); + repo.commit(); + DataWord tombstone = RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(seeded, new DataWord(0)); + Assert.assertNull(tombstone); + + byte[] caller = Hex.decode(OWNER_ADDRESS); + Runtime seededCall = TvmTestUtils.processTransactionAndReturnRuntime( + TvmTestUtils.generateTriggerSmartContractAndGetTransaction( + caller, seeded, new byte[0], 0, FEE_LIMIT), + dbManager, null); + Runtime freshCall = TvmTestUtils.processTransactionAndReturnRuntime( + TvmTestUtils.generateTriggerSmartContractAndGetTransaction( + caller, fresh, new byte[0], 0, FEE_LIMIT), + dbManager, null); + Assert.assertEquals(SUCCESS, seededCall.getResult().getResultCode()); + Assert.assertEquals(SUCCESS, freshCall.getResult().getResultCode()); + Assert.assertEquals(freshCall.getResult().getEnergyUsed(), + seededCall.getResult().getEnergyUsed()); + DataWord written = RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(seeded, new DataWord(0)); + Assert.assertEquals(1L, written.longValue()); + } finally { + dbManager.getDynamicPropertiesStore().saveAllowOptimizeTvmStorage(0); + dbManager.getDynamicPropertiesStore().saveAllowTvmConstantinople(0); + } + } + + @Test + public void distinctSlotsStaySuccessfulAfterFork() throws Exception { + activateFork(); + Runtime runtime = deploy(NON_ALIAS); + Assert.assertEquals(SUCCESS, runtime.getResult().getResultCode()); + Assert.assertNull(runtime.getResult().getException()); + } + + @Test + public void aliasedSstoreTimesOutAfterFork() throws Exception { + activateFork(); + dbManager.getDynamicPropertiesStore().saveAllowTvmCompatibleEvm(0); + VMConfig.initAllowTvmCompatibleEvm(0); + byte[] address = account("00000000000000000000000000000000000000c2"); + rootRepository.createAccount(address, AccountType.Normal); + byte[] slotA = word(1); + byte[] slotB = word(1); + slotB[15] = 1; + rootRepository.putStorageValue(address, new DataWord(slotA), new DataWord(1)); + try { + rootRepository.putStorageValue(address, new DataWord(slotB), new DataWord(2)); + Assert.fail("aliased sstore must time out"); + } catch (OutOfTimeException expected) { + Assert.assertNotNull(expected); + } + + Runtime runtime = deploy(ALIAS); + Assert.assertEquals(OUT_OF_TIME, runtime.getResult().getResultCode()); + Assert.assertTrue(runtime.getResult().getException() instanceof OutOfTimeException); + } + + private Runtime deploy(String codeHex) throws Exception { + return deploy("Alias", codeHex); + } + + private Runtime deploy(String name, String codeHex) throws Exception { + byte[] caller = Hex.decode(OWNER_ADDRESS); + Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + name, caller, "[]", codeHex, 0, FEE_LIMIT, 100, null, 0); + return TvmTestUtils.processTransactionAndReturnRuntime(trx, dbManager, null); + } + + private void activateFork() { + ForkController.instance().init(chainBaseManager); + byte[] stats = new byte[27]; + Arrays.fill(stats, (byte) 1); + dbManager.getDynamicPropertiesStore().statsByVersion( + ForkBlockVersionEnum.VERSION_4_8_2_3.getValue(), stats); + long interval = dbManager.getDynamicPropertiesStore().getMaintenanceTimeInterval(); + long hardForkTime = ((ForkBlockVersionEnum.VERSION_4_8_2_3.getHardForkTime() - 1) + / interval + 1) * interval; + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(hardForkTime + 1); + Assert.assertTrue(ForkController.instance().pass(ForkBlockVersionEnum.VERSION_4_8_2_3)); + } + + private static byte[] account(String tail) { + return Hex.decode("41" + tail); + } + + private static byte[] word(int value) { + byte[] out = new byte[32]; + out[31] = (byte) value; + return out; + } + + private static byte[] optimizedKey(byte[] address, byte[] slot) { + byte[] addrHash = Hash.sha3(address); + byte[] key = new byte[48]; + System.arraycopy(addrHash, 0, key, 0, 16); + System.arraycopy(Hash.sha3(ByteUtil.merge(addrHash, slot)), 0, key, 16, 32); + return key; + } + + private static byte[] legacyKey(byte[] address, byte[] slot) { + byte[] key = new byte[32]; + System.arraycopy(Hash.sha3(address), 0, key, 0, 16); + System.arraycopy(slot, 16, key, 16, 16); + return key; + } +} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VMConfigIsolationTest.java b/framework/src/test/java/org/tron/common/runtime/vm/VMConfigIsolationTest.java index 845db6dd6af..6dc561034db 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VMConfigIsolationTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VMConfigIsolationTest.java @@ -103,6 +103,7 @@ private static VMConfig.Snapshot snapshotGlobal() { snapshot.allowTvmSelfdestructRestriction = VMConfig.allowTvmSelfdestructRestriction(); snapshot.allowTvmOsaka = VMConfig.allowTvmOsaka(); snapshot.allowHardenResourceCalculation = VMConfig.allowHardenResourceCalculation(); + snapshot.allowOptimizeTvmStorage = VMConfig.allowOptimizeTvmStorage(); return snapshot; } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java b/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java index 2c7aa238033..b949cbd8dc8 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java @@ -217,7 +217,7 @@ public void testWitnessArrayLargerThanAmountArray() { @Test public void testOperationRegistryWithoutOsaka() { VMConfig.initAllowTvmOsaka(0); - JumpTable table = OperationRegistry.getTable(); + JumpTable table = OperationRegistry.prepareAndGetTable(false); Operation voteOp = table.get(Op.VOTEWITNESS); assertTrue(voteOp.isEnabled()); @@ -233,7 +233,7 @@ public void testOperationRegistryWithoutOsaka() { public void testOperationRegistryWithOsaka() { VMConfig.initAllowTvmOsaka(1); try { - JumpTable table = OperationRegistry.getTable(); + JumpTable table = OperationRegistry.prepareAndGetTable(false); Operation voteOp = table.get(Op.VOTEWITNESS); assertTrue(voteOp.isEnabled()); diff --git a/framework/src/test/java/org/tron/common/utils/PeerManagerStateResetter.java b/framework/src/test/java/org/tron/common/utils/PeerManagerStateResetter.java new file mode 100644 index 00000000000..b4766115f2d --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/PeerManagerStateResetter.java @@ -0,0 +1,99 @@ +package org.tron.common.utils; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; +import org.springframework.util.ReflectionUtils; +import org.tron.common.es.ExecutorServiceManager; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; +import org.tron.protos.Protocol.ReasonCode; + +/** + * Test source-set utility: restores {@link PeerManager} to a cold-start state. + * + *

    {@link PeerManager#close()} neither clears the raw static peers/counters nor rebuilds the + * static executor, and tests share one JVM across Spring contexts. + * + *

    The old executor is drained to termination before touching any state: {@code + * check()} is not synchronized (it snapshots peers, then removes entries and decrements + * counters), so a task left running would decrement the counters zeroed in step 4 and leave + * them negative; shutdown alone does not guarantee that, so reset fails if termination cannot + * be confirmed. + * Residual peers are disconnected before the raw list is cleared because {@code close()} may + * fail midway and leave live channels that a bare {@code clear()} would orphan; each peer is + * handled defensively (null channel tolerated, per-peer catch). A fresh executor is then + * installed (lazy thread, no tasks until the next {@code init()}). + * + *

    Wired broadly from BaseTest/BaseMethodTest against unknown prior pollution; the reset is + * idempotent and cheap for tests that never use PeerManager. Remove this utility once + * production {@code close()}/{@code init()} is restart-safe. + */ +public final class PeerManagerStateResetter { + + private static final String EXECUTOR_NAME = "peer-manager"; + + private PeerManagerStateResetter() { + } + + public static synchronized void reset() { + // 1) Drain the old executor first: let running/queued check() tasks die out so they + // cannot interleave with the list/counter reset below. Gate on isTerminated(), not + // isShutdown(): shutdown() still lets a running check() finish asynchronously, and + // check() decrements the counters even when its peers.remove() is a no-op. If + // termination cannot be confirmed, fail the setup instead of resetting anyway. + ScheduledExecutorService executor = getFieldValue("executor"); + if (executor != null && !executor.isTerminated()) { + ExecutorServiceManager.shutdownAndAwaitTermination(executor, EXECUTOR_NAME); + if (!executor.isTerminated()) { + throw new IllegalStateException( + "peer-manager executor did not terminate; refusing to reset shared state"); + } + } + // 2) Unconditionally install a fresh executor (the old one may be shut down or null); + // its thread is created lazily. + setFieldValue("executor", + ExecutorServiceManager.newSingleThreadScheduledExecutor(EXECUTOR_NAME)); + + // 3) Release residual live connections before clearing the raw list. + List peers = getFieldValue("peers"); + if (peers == null) { + setFieldValue("peers", Collections.synchronizedList(new ArrayList())); + } else { + for (PeerConnection peer : new ArrayList<>(peers)) { + try { + if (!peer.isDisconnect()) { + peer.disconnect(ReasonCode.PEER_QUITING); + if (peer.getChannel() != null) { + peer.getChannel().close(); + } + } + } catch (Exception e) { + // best effort: a single corrupted leftover peer must not fail the reset + } + } + peers.clear(); + } + + // 4) Zero the counters; old tasks can no longer decrement them at this point. + AtomicInteger active = PeerManager.getActivePeersCount(); + AtomicInteger passive = PeerManager.getPassivePeersCount(); + active.set(0); + passive.set(0); + } + + private static T getFieldValue(String fieldName) { + Field field = ReflectionUtils.findField(PeerManager.class, fieldName); + ReflectionUtils.makeAccessible(field); + return (T) ReflectionUtils.getField(field, null); + } + + private static void setFieldValue(String fieldName, Object value) { + Field field = ReflectionUtils.findField(PeerManager.class, fieldName); + ReflectionUtils.makeAccessible(field); + ReflectionUtils.setField(field, null, value); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/PeerManagerStateResetterTest.java b/framework/src/test/java/org/tron/common/utils/PeerManagerStateResetterTest.java new file mode 100644 index 00000000000..d7316c06333 --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/PeerManagerStateResetterTest.java @@ -0,0 +1,79 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; + +/** + * Pins the cold-start guarantees of {@link PeerManagerStateResetter#reset()}: after a reset the + * shared peers list is empty, both counters are zero, and the installed executor is fresh — + * including on the path where the old executor was already shut down but might still be + * draining a {@code check()} task. + */ +public class PeerManagerStateResetterTest { + + @Test + @SuppressWarnings("unchecked") + public void testResetRestoresColdStartState() throws Exception { + Field peersField = PeerManager.class.getDeclaredField("peers"); + peersField.setAccessible(true); + List peers = (List) peersField.get(null); + peers.clear(); + PeerConnection stalePeer = Mockito.mock(PeerConnection.class); + Mockito.when(stalePeer.isDisconnect()).thenReturn(true); + peers.add(stalePeer); + AtomicInteger active = PeerManager.getActivePeersCount(); + AtomicInteger passive = PeerManager.getPassivePeersCount(); + active.set(7); + passive.set(3); + + PeerManagerStateResetter.reset(); + + assertEquals(0, peers.size()); + assertEquals(0, active.get()); + assertEquals(0, passive.get()); + Field executorField = PeerManager.class.getDeclaredField("executor"); + executorField.setAccessible(true); + ScheduledExecutorService executor = (ScheduledExecutorService) executorField.get(null); + assertFalse(executor.isShutdown()); + } + + // pin: reset() clears PeerManager statics by hardcoded field names — a new static field + // silently leaks across tests unless it gets resetter coverage or an allowlist entry here. + @Test + public void resetterCoversAllPeerManagerStaticFields() { + // fields reset() actually drains/rebuilds/clears/zeroes + Set handled = new HashSet<>(Arrays.asList( + "peers", "executor", "activePeersCount", "passivePeersCount")); + // fields intentionally untouched: constants / config that never mutates across tests + Set allowed = new HashSet<>(Arrays.asList( + "esName", "DISCONNECTION_TIME_OUT", "logger")); + + List unclassified = new java.util.ArrayList<>(); + for (Field field : PeerManager.class.getDeclaredFields()) { + // skip compiler/JaCoCo-generated synthetic fields (e.g. $jacocoData) — not business state + if (!Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) { + continue; + } + String name = field.getName(); + if (!handled.contains(name) && !allowed.contains(name)) { + unclassified.add(name + " (" + field.getType().getSimpleName() + ")"); + } + } + assertEquals("new static field needs resetter coverage or explicit allowlist entry: " + + unclassified, Collections.emptyList(), unclassified); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java b/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java index 4de441d940d..34c7536ebd0 100644 --- a/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java +++ b/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java @@ -9,7 +9,6 @@ import java.util.List; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -42,7 +41,7 @@ public void shuffle() { final List witnessCapsuleListBefore = this.getWitnessList(); logger.info("updateWitnessSchedule,before: " + getWitnessStringList(witnessCapsuleListBefore)); final List witnessCapsuleListAfter = new RandomGenerator() - .shuffle(witnessCapsuleListBefore, DateTime.now().getMillis()); + .shuffle(witnessCapsuleListBefore, System.currentTimeMillis()); logger.info("updateWitnessSchedule,after: " + getWitnessStringList(witnessCapsuleListAfter)); } diff --git a/framework/src/test/java/org/tron/common/utils/client/GrpcClient.java b/framework/src/test/java/org/tron/common/utils/client/GrpcClient.java index 139485e4e2b..c8dd6711f42 100644 --- a/framework/src/test/java/org/tron/common/utils/client/GrpcClient.java +++ b/framework/src/test/java/org/tron/common/utils/client/GrpcClient.java @@ -8,7 +8,6 @@ import org.tron.api.GrpcAPI; import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.GrpcAPI.AccountPaginated; import org.tron.api.GrpcAPI.AssetIssueList; import org.tron.api.GrpcAPI.BlockLimit; import org.tron.api.GrpcAPI.BlockList; @@ -17,9 +16,7 @@ import org.tron.api.GrpcAPI.NodeList; import org.tron.api.GrpcAPI.NumberMessage; import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.GrpcAPI.TransactionList; import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletExtensionGrpc; import org.tron.api.WalletGrpc; import org.tron.api.WalletSolidityGrpc; import org.tron.common.utils.ByteArray; @@ -42,7 +39,6 @@ public class GrpcClient { private ManagedChannel channelSolidity = null; private WalletGrpc.WalletBlockingStub blockingStubFull = null; private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; // public GrpcClient(String host, int port) { // channel = ManagedChannelBuilder.forAddress(host, port) @@ -67,7 +63,6 @@ public GrpcClient(String fullnode, String soliditynode) { .usePlaintext() .build(); blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); } } @@ -284,56 +279,6 @@ public Optional listNodes() { } }*/ - /* public Optional getAssetIssueListByTimestamp(long time) { - NumberMessage.Builder timeStamp = NumberMessage.newBuilder(); - timeStamp.setNum(time); - AssetIssueList assetIssueList = blockingStubSolidity - .getAssetIssueListByTimestamp(timeStamp.build()); - return Optional.ofNullable(assetIssueList); - }*/ - /* public Optional getTransactionsByTimestamp( - long start, long end, int offset , int limit) { - TimeMessage.Builder timeMessage = TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - TimePaginatedMessage.Builder timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(offset); - timePageMessage.setLimit(limit); - TransactionList transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - return Optional.ofNullable(transactionList); - }*/ - - /** - * constructor. - */ - - public Optional getTransactionsFromThis(byte[] address) { - ByteString addressBs = ByteString.copyFrom(address); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder builder = AccountPaginated.newBuilder().setAccount(account); - builder.setLimit(1000); - builder.setOffset(0); - TransactionList transactionList = blockingStubExtension - .getTransactionsFromThis(builder.build()); - return Optional.ofNullable(transactionList); - } - - /** - * constructor. - */ - - public Optional getTransactionsToThis(byte[] address) { - ByteString addressBs = ByteString.copyFrom(address); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder builder = AccountPaginated.newBuilder().setAccount(account); - builder.setLimit(1000); - builder.setOffset(0); - TransactionList transactionList = blockingStubExtension.getTransactionsToThis(builder.build()); - return Optional.ofNullable(transactionList); - } - /* public Optional getTransactionById(String txID){ ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txID)); BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); diff --git a/framework/src/test/java/org/tron/common/utils/client/WalletClient.java b/framework/src/test/java/org/tron/common/utils/client/WalletClient.java index 9d9a68da49d..168099182f5 100644 --- a/framework/src/test/java/org/tron/common/utils/client/WalletClient.java +++ b/framework/src/test/java/org/tron/common/utils/client/WalletClient.java @@ -22,7 +22,6 @@ import org.tron.api.GrpcAPI.AssetIssueList; import org.tron.api.GrpcAPI.BlockList; import org.tron.api.GrpcAPI.NodeList; -import org.tron.api.GrpcAPI.TransactionList; import org.tron.api.GrpcAPI.WitnessList; import org.tron.common.crypto.ECKey; import org.tron.common.parameter.CommonParameter; @@ -647,14 +646,6 @@ public static Optional listNodes() { return rpcCli.listNodes(); } - public static Optional getTransactionsFromThis(byte[] address) { - return rpcCli.getTransactionsFromThis(address); - } - - public static Optional getTransactionsToThis(byte[] address) { - return rpcCli.getTransactionsToThis(address); - } - public static Block getBlock(long blockNum) { return rpcCli.getBlock(blockNum); } @@ -701,15 +692,6 @@ private Transaction signTransaction(Transaction transaction) { return TransactionUtils.sign(transaction, this.ecKey); } - /* public static Optional getAssetIssueListByTimestamp(long timestamp) { - return rpcCli.getAssetIssueListByTimestamp(timestamp); - }*/ - - /* public static Optional getTransactionsByTimestamp( - long start, long end, int offset, int limit) { - return rpcCli.getTransactionsByTimestamp(start, end, offset, limit); - }*/ - /** * constructor. */ diff --git a/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java b/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java index cea17b0c033..0f7cf9eeb7e 100644 --- a/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java @@ -1910,50 +1910,6 @@ public static HttpResponse getTransactionCountByBlocknumFromPbft( return response; } - /** constructor. */ - public static HttpResponse getTransactionsFromThisFromSolidity( - String httpSolidityNode, byte[] fromAddress, long offset, long limit) { - try { - Map map1 = new HashMap(); - Map map = new HashMap(); - map1.put("address", ByteArray.toHexString(fromAddress)); - map.put("account", map1); - map.put("offset", offset); - map.put("limit", limit); - String requestUrl = "http://" + httpSolidityNode + "/walletextension/gettransactionsfromthis"; - String jsonStr = new Gson().toJson(map); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** constructor. */ - public static HttpResponse getTransactionsToThisFromSolidity( - String httpSolidityNode, byte[] toAddress, long offset, long limit) { - try { - Map map1 = new HashMap(); - Map map = new HashMap(); - map1.put("address", ByteArray.toHexString(toAddress)); - map.put("account", map1); - map.put("offset", offset); - map.put("limit", limit); - String requestUrl = "http://" + httpSolidityNode + "/walletextension/gettransactionstothis"; - String jsonStr = new Gson().toJson(map); - JsonObject jsonObj = new JsonParser().parse(jsonStr).getAsJsonObject(); - response = createConnect(requestUrl, jsonObj); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - /** constructor. */ public static HttpResponse getAssetIssueByName(String httpNode, String name) { try { diff --git a/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java b/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java index cf652af3650..622d20ae7d2 100755 --- a/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java +++ b/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java @@ -5,8 +5,8 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; import java.nio.charset.StandardCharsets; +import java.time.ZonedDateTime; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -64,8 +64,8 @@ public class BandwidthProcessorTest extends BaseTest { TO_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; ASSET_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; ASSET_ADDRESS_V2 = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a7890"; - START_TIME = DateTime.now().minusDays(1).getMillis(); - END_TIME = DateTime.now().getMillis(); + START_TIME = ZonedDateTime.now().minusDays(1).toInstant().toEpochMilli(); + END_TIME = System.currentTimeMillis(); } /** @@ -616,7 +616,7 @@ public void sameTokenNameCloseConsumeSuccess() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); ownerCapsule.setBalance(10_000_000L); - long expireTime = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime = System.currentTimeMillis() + 6 * 86_400_000; ownerCapsule.setFrozenForBandwidth(2_000_000L, expireTime); chainBaseManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); @@ -627,7 +627,7 @@ public void sameTokenNameCloseConsumeSuccess() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); toAddressCapsule.setBalance(10_000_000L); - long expireTime2 = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime2 = System.currentTimeMillis() + 6 * 86_400_000; toAddressCapsule.setFrozenForBandwidth(2_000_000L, expireTime2); chainBaseManager.getAccountStore().put(toAddressCapsule.getAddress().toByteArray(), toAddressCapsule); @@ -731,7 +731,7 @@ public void sameTokenNameOpenConsumeSuccess() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); ownerCapsule.setBalance(10_000_000L); - long expireTime = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime = System.currentTimeMillis() + 6 * 86_400_000; ownerCapsule.setFrozenForBandwidth(2_000_000L, expireTime); chainBaseManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); @@ -742,7 +742,7 @@ public void sameTokenNameOpenConsumeSuccess() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); toAddressCapsule.setBalance(10_000_000L); - long expireTime2 = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime2 = System.currentTimeMillis() + 6 * 86_400_000; toAddressCapsule.setFrozenForBandwidth(2_000_000L, expireTime2); chainBaseManager.getAccountStore().put(toAddressCapsule.getAddress().toByteArray(), toAddressCapsule); @@ -816,7 +816,7 @@ public void sameTokenNameCloseTransferToAccountNotExist() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); ownerCapsule.setBalance(10_000_000L); - long expireTime = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime = System.currentTimeMillis() + 6 * 86_400_000; ownerCapsule.setFrozenForBandwidth(2_000_000L, expireTime); chainBaseManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); @@ -827,7 +827,7 @@ public void sameTokenNameCloseTransferToAccountNotExist() { AccountType.Normal, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); toAddressCapsule.setBalance(10_000_000L); - long expireTime2 = DateTime.now().getMillis() + 6 * 86_400_000; + long expireTime2 = System.currentTimeMillis() + 6 * 86_400_000; toAddressCapsule.setFrozenForBandwidth(2_000_000L, expireTime2); chainBaseManager.getAccountStore().delete(toAddressCapsule.getAddress().toByteArray()); diff --git a/framework/src/test/java/org/tron/core/WalletTest.java b/framework/src/test/java/org/tron/core/WalletTest.java index 9dbab338b67..7215a287912 100644 --- a/framework/src/test/java/org/tron/core/WalletTest.java +++ b/framework/src/test/java/org/tron/core/WalletTest.java @@ -30,12 +30,12 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import javax.annotation.Resource; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; -import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; @@ -113,21 +113,29 @@ public class WalletTest extends BaseTest { public static final long BLOCK_NUM_THREE = 3; public static final long BLOCK_NUM_FOUR = 4; public static final long BLOCK_NUM_FIVE = 5; - public static final long BLOCK_TIMESTAMP_ONE = DateTime.now().minusDays(4).getMillis(); - public static final long BLOCK_TIMESTAMP_TWO = DateTime.now().minusDays(3).getMillis(); - public static final long BLOCK_TIMESTAMP_THREE = DateTime.now().minusDays(2).getMillis(); - public static final long BLOCK_TIMESTAMP_FOUR = DateTime.now().minusDays(1).getMillis(); - public static final long BLOCK_TIMESTAMP_FIVE = DateTime.now().getMillis(); + public static final long BLOCK_TIMESTAMP_ONE = + ZonedDateTime.now().minusDays(4).toInstant().toEpochMilli(); + public static final long BLOCK_TIMESTAMP_TWO = + ZonedDateTime.now().minusDays(3).toInstant().toEpochMilli(); + public static final long BLOCK_TIMESTAMP_THREE = + ZonedDateTime.now().minusDays(2).toInstant().toEpochMilli(); + public static final long BLOCK_TIMESTAMP_FOUR = + ZonedDateTime.now().minusDays(1).toInstant().toEpochMilli(); + public static final long BLOCK_TIMESTAMP_FIVE = System.currentTimeMillis(); public static final long BLOCK_WITNESS_ONE = 12; public static final long BLOCK_WITNESS_TWO = 13; public static final long BLOCK_WITNESS_THREE = 14; public static final long BLOCK_WITNESS_FOUR = 15; public static final long BLOCK_WITNESS_FIVE = 16; - public static final long TRANSACTION_TIMESTAMP_ONE = DateTime.now().minusDays(4).getMillis(); - public static final long TRANSACTION_TIMESTAMP_TWO = DateTime.now().minusDays(3).getMillis(); - public static final long TRANSACTION_TIMESTAMP_THREE = DateTime.now().minusDays(2).getMillis(); - public static final long TRANSACTION_TIMESTAMP_FOUR = DateTime.now().minusDays(1).getMillis(); - public static final long TRANSACTION_TIMESTAMP_FIVE = DateTime.now().getMillis(); + public static final long TRANSACTION_TIMESTAMP_ONE = + ZonedDateTime.now().minusDays(4).toInstant().toEpochMilli(); + public static final long TRANSACTION_TIMESTAMP_TWO = + ZonedDateTime.now().minusDays(3).toInstant().toEpochMilli(); + public static final long TRANSACTION_TIMESTAMP_THREE = + ZonedDateTime.now().minusDays(2).toInstant().toEpochMilli(); + public static final long TRANSACTION_TIMESTAMP_FOUR = + ZonedDateTime.now().minusDays(1).toInstant().toEpochMilli(); + public static final long TRANSACTION_TIMESTAMP_FIVE = System.currentTimeMillis(); @Resource private Wallet wallet; private static Block block1; diff --git a/framework/src/test/java/org/tron/core/actuator/ContractHashValidationTest.java b/framework/src/test/java/org/tron/core/actuator/ContractHashValidationTest.java new file mode 100644 index 00000000000..a2dd0a51e4e --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/ContractHashValidationTest.java @@ -0,0 +1,67 @@ +package org.tron.core.actuator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import org.junit.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.tron.common.utils.ForkController; +import org.tron.core.config.Parameter.ForkBlockVersionEnum; +import org.tron.core.vm.program.Program.OutOfTimeException; +import org.tron.protos.contract.SmartContractOuterClass.SmartContract; + +public class ContractHashValidationTest { + + @Test + public void acceptsHashFieldsBeforeActivation() { + SmartContract contract = SmartContract.newBuilder() + .setCodeHash(ByteString.copyFromUtf8("code")) + .setTrxHash(ByteString.copyFromUtf8("transaction")) + .build(); + + runWithActivation(false, () -> VMActuator.checkContractHashFields(contract)); + } + + @Test + public void rejectsCodeHashAfterActivation() { + SmartContract contract = SmartContract.newBuilder() + .setCodeHash(ByteString.copyFromUtf8("code")) + .build(); + + OutOfTimeException exception = assertThrows(OutOfTimeException.class, + () -> runWithActivation(true, () -> VMActuator.checkContractHashFields(contract))); + + assertEquals("CPU timeout for contract hash fields", exception.getMessage()); + } + + @Test + public void rejectsTransactionHashAfterActivation() { + SmartContract contract = SmartContract.newBuilder() + .setTrxHash(ByteString.copyFromUtf8("transaction")) + .build(); + + OutOfTimeException exception = assertThrows(OutOfTimeException.class, + () -> runWithActivation(true, () -> VMActuator.checkContractHashFields(contract))); + + assertEquals("CPU timeout for contract hash fields", exception.getMessage()); + } + + @Test + public void acceptsEmptyHashFieldsAfterActivation() { + runWithActivation(true, + () -> VMActuator.checkContractHashFields(SmartContract.getDefaultInstance())); + } + + private void runWithActivation(boolean activated, Runnable action) { + ForkController controller = mock(ForkController.class); + when(controller.pass(ForkBlockVersionEnum.VERSION_4_8_2_2)).thenReturn(activated); + try (MockedStatic controllerMock = Mockito.mockStatic(ForkController.class)) { + controllerMock.when(ForkController::instance).thenReturn(controller); + action.run(); + } + } +} diff --git a/framework/src/test/java/org/tron/core/actuator/ContractNameValidationTest.java b/framework/src/test/java/org/tron/core/actuator/ContractNameValidationTest.java new file mode 100644 index 00000000000..e172829e7d6 --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/ContractNameValidationTest.java @@ -0,0 +1,65 @@ +package org.tron.core.actuator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.Test; +import org.junit.function.ThrowingRunnable; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.tron.common.utils.ForkController; +import org.tron.core.config.Parameter.ForkBlockVersionEnum; +import org.tron.core.exception.ContractValidateException; +import org.tron.protos.contract.SmartContractOuterClass.SmartContract; + +public class ContractNameValidationTest { + + @Test + public void acceptsThirtyTwoByteNameAfterActivation() throws Throwable { + SmartContract contract = contractWithName("12345678901234567890123456789012"); + + runWithActivation(true, () -> VMActuator.checkContractNameLength(contract)); + } + + @Test + public void rejectsThirtyThreeByteNameAfterActivation() { + SmartContract contract = contractWithName("123456789012345678901234567890123"); + + ContractValidateException exception = assertThrows(ContractValidateException.class, + () -> runWithActivation(true, () -> VMActuator.checkContractNameLength(contract))); + + assertEquals("contractName's length cannot be greater than 32", exception.getMessage()); + } + + @Test + public void countsMultibyteNameUsingProtobufBytesAfterActivation() { + SmartContract contract = contractWithName("合合合合合合合合合合合"); + assertEquals(33, contract.getNameBytes().size()); + + assertThrows(ContractValidateException.class, + () -> runWithActivation(true, () -> VMActuator.checkContractNameLength(contract))); + } + + @Test + public void preservesNameValidationBeforeActivation() { + SmartContract contract = contractWithName("123456789012345678901234567890123"); + + assertThrows(ContractValidateException.class, + () -> runWithActivation(false, () -> VMActuator.checkContractNameLength(contract))); + } + + private SmartContract contractWithName(String name) { + return SmartContract.newBuilder().setName(name).build(); + } + + private void runWithActivation(boolean activated, ThrowingRunnable action) throws Throwable { + ForkController controller = mock(ForkController.class); + when(controller.pass(ForkBlockVersionEnum.VERSION_4_8_2_2)).thenReturn(activated); + try (MockedStatic controllerMock = Mockito.mockStatic(ForkController.class)) { + controllerMock.when(ForkController::instance).thenReturn(controller); + action.run(); + } + } +} diff --git a/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java index 5c168f51bee..4af63285b1e 100755 --- a/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java @@ -2,7 +2,7 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import org.joda.time.DateTime; +import java.time.ZonedDateTime; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -403,8 +403,8 @@ public void sameTokenNameOpenRightAssetIssue() { */ @Test public void sameTokenNameCloseAssetIssueTimeRight() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), now.toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(1000L)); @@ -436,8 +436,8 @@ public void sameTokenNameCloseAssetIssueTimeRight() { @Test public void sameTokenNameOpenAssetIssueTimeRight() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), now.toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(1000L)); @@ -470,8 +470,8 @@ public void sameTokenNameOpenAssetIssueTimeRight() { */ @Test public void sameTokenNameCloseAssetIssueTimeLeft() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), now.toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(1000L)); @@ -504,8 +504,8 @@ public void sameTokenNameCloseAssetIssueTimeLeft() { @Test public void sameTokenNameOpenAssetIssueTimeLeft() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), now.toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(1000L)); @@ -605,8 +605,9 @@ public void sameTokenNameOpenExchangeDevisibleTest() { */ @Test public void sameTokenNameCloseNegativeAmountTest() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(-999L)); @@ -639,8 +640,9 @@ public void sameTokenNameCloseNegativeAmountTest() { @Test public void sameTokenNameOpenNegativeAmountTest() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(-999L)); @@ -675,8 +677,9 @@ public void sameTokenNameOpenNegativeAmountTest() { */ @Test public void sameTokenNameCloseZeroAmountTest() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(0)); @@ -709,8 +712,9 @@ public void sameTokenNameCloseZeroAmountTest() { @Test public void sameTokenNameOpenZeroAmountTest() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(0)); @@ -746,8 +750,9 @@ public void sameTokenNameOpenZeroAmountTest() { */ @Test public void sameTokenNameCloseNoExitOwnerTest() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager) .setAny(getContractWithOwner(101, NOT_EXIT_ADDRESS)); @@ -782,8 +787,9 @@ public void sameTokenNameCloseNoExitOwnerTest() { @Test public void sameTokenNameOpenNoExitOwnerTest() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager) .setAny(getContractWithOwner(101, NOT_EXIT_ADDRESS)); @@ -1310,8 +1316,9 @@ public void sameTokenNameOpenNotEnoughAssetTest() { */ @Test public void sameTokenNameCloseNoneExistAssetTest() { - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager) .setAny(getContract(1, "TTTTTTTTTTTT")); @@ -1346,8 +1353,9 @@ public void sameTokenNameCloseNoneExistAssetTest() { @Test public void sameTokenNameOpenNoneExistAssetTest() { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - DateTime now = DateTime.now(); - initAssetIssue(now.minusDays(1).getMillis(), now.plusDays(1).getMillis()); + ZonedDateTime now = ZonedDateTime.now(); + initAssetIssue(now.minusDays(1).toInstant().toEpochMilli(), + now.plusDays(1).toInstant().toEpochMilli()); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager) .setAny(getContract(1, "TTTTTTTTTTTT")); diff --git a/framework/src/test/java/org/tron/core/config/ConfigurationTest.java b/framework/src/test/java/org/tron/core/config/ConfigurationTest.java index b066bc1e6be..b23f350716c 100644 --- a/framework/src/test/java/org/tron/core/config/ConfigurationTest.java +++ b/framework/src/test/java/org/tron/core/config/ConfigurationTest.java @@ -35,6 +35,7 @@ import org.tron.common.crypto.ECKey; import org.tron.common.utils.ByteArray; import org.tron.core.Wallet; +import org.tron.core.config.args.StorageConfig; @Slf4j public class ConfigurationTest { @@ -91,4 +92,20 @@ public void getConfigurationWhenOnlyConfFileName() { assertTrue(config.hasPath("seed.node")); assertTrue(config.hasPath("genesis.block")); } + + @Test + public void defaultConfigShouldPreserveEffectiveRocksDbSettings() { + Config config = Configuration.getByFileName("config.conf"); + StorageConfig.DbSettingsConfig settings = StorageConfig.fromConfig(config).getDbSettings(); + + assertTrue(config.hasPath("storage.dbSettings.blocksize")); + assertEquals(64, settings.getBlocksize()); + assertEquals(7, settings.getLevelNumber()); + assertEquals(256, settings.getMaxBytesForLevelBase()); + assertEquals(10, settings.getMaxBytesForLevelMultiplier(), 0.01); + assertEquals(4, settings.getLevel0FileNumCompactionTrigger()); + assertEquals(256, settings.getTargetFileSizeBase()); + assertEquals(1, settings.getTargetFileSizeMultiplier()); + assertEquals(5000, settings.getMaxOpenFiles()); + } } diff --git a/framework/src/test/java/org/tron/core/config/args/ArgsTest.java b/framework/src/test/java/org/tron/core/config/args/ArgsTest.java index 36b8a3269c1..8d6b0bfaa91 100644 --- a/framework/src/test/java/org/tron/core/config/args/ArgsTest.java +++ b/framework/src/test/java/org/tron/core/config/args/ArgsTest.java @@ -15,6 +15,10 @@ package org.tron.core.config.args; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import com.google.common.collect.Lists; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; @@ -31,6 +35,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.slf4j.LoggerFactory; import org.tron.common.TestConstants; import org.tron.common.args.GenesisBlock; import org.tron.common.parameter.CommonParameter; @@ -369,6 +374,46 @@ public void testConfigStorageDefaults() { Args.clearParam(); } + /** + * The removed node.walletExtensionApi key must stay harmless in operator configs: + * binding ignores it and fromConfig logs a removal warning. Lives here rather than + * NodeConfigTest because module jacoco reports only aggregate framework execution data. + */ + @Test + public void testRemovedWalletExtensionApiKeyWarnsWhenTrue() { + Assert.assertEquals(1, countWalletExtensionApiWarnings("node { walletExtensionApi = true }")); + } + + @Test + public void testRemovedWalletExtensionApiKeyWarnsWhenFalse() { + Assert.assertEquals(1, countWalletExtensionApiWarnings("node { walletExtensionApi = false }")); + } + + @Test + public void testNoWalletExtensionApiWarningWhenKeyAbsent() { + Assert.assertEquals(0, countWalletExtensionApiWarnings("")); + } + + private static long countWalletExtensionApiWarnings(String hocon) { + Config config = ConfigFactory.parseString(hocon) + .withFallback(ConfigFactory.defaultReference()); + Logger logger = (Logger) LoggerFactory.getLogger(NodeConfig.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + Assert.assertNotNull(NodeConfig.fromConfig(config)); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + return appender.list.stream() + .filter(e -> e.getLevel() == Level.WARN) + .filter(e -> e.getFormattedMessage() + .contains("[node.walletExtensionApi] has been removed and is ignored")) + .count(); + } + // =========================================================================== // Boundary tests for node.fetchBlock.timeout clamping. // @@ -519,6 +564,64 @@ public void testMaxMessageSizeNegativeValueRejected() { } } + @Test + public void testDnsPublishRejectsInvalidServerTypeWithParameterInitError() { + Config config = dnsPublishConfig( + "node.dns.serverType", "unsupported"); + + TronError error = Assert.assertThrows(TronError.class, + () -> Args.loadDnsPublishConfig(NodeConfig.fromConfig(config))); + + Assert.assertEquals(TronError.ErrCode.PARAMETER_INIT, error.getErrCode()); + Assert.assertEquals("Check node.dns.serverType, must be aws or aliyun", + error.getMessage()); + } + + @Test + public void testDnsPublishRejectsEmptyRequiredParameterWithParameterInitError() { + Config config = dnsPublishConfig("node.dns.dnsDomain", ""); + + TronError error = Assert.assertThrows(TronError.class, + () -> Args.loadDnsPublishConfig(NodeConfig.fromConfig(config))); + + Assert.assertEquals(TronError.ErrCode.PARAMETER_INIT, error.getErrCode()); + Assert.assertEquals("Check node.dns.dnsDomain, must not be null or empty", + error.getMessage()); + } + + @Test + public void testCommitteeConfigRejectsOldRewardOptimizationWithoutPrerequisite() { + Map configMap = new HashMap<>(); + configMap.put("storage.db.directory", "database"); + configMap.put("committee.allowOldRewardOpt", 1); + Config config = ConfigFactory.parseMap(configMap) + .withFallback(ConfigFactory.defaultReference()); + + try { + TronError error = Assert.assertThrows(TronError.class, + () -> Args.applyConfigParams(config)); + + Assert.assertEquals(TronError.ErrCode.PARAMETER_INIT, error.getErrCode()); + } finally { + Args.clearParam(); + } + } + + private Config dnsPublishConfig(String key, String value) { + Map configMap = new HashMap<>(); + configMap.put("node.dns.publish", true); + configMap.put("node.dns.dnsDomain", "nodes.example.org"); + configMap.put("node.dns.dnsPrivate", + "1234567890123456789012345678901234567890123456789012345678901234"); + configMap.put("node.dns.serverType", "aliyun"); + configMap.put("node.dns.accessKeyId", "access-key-id"); + configMap.put("node.dns.accessKeySecret", "access-key-secret"); + configMap.put("node.dns.aliyunDnsEndpoint", "dns.aliyuncs.com"); + configMap.put(key, value); + return ConfigFactory.parseMap(configMap) + .withFallback(ConfigFactory.defaultReference()); + } + @Test public void testRpcMaxMessageSizeExceedsIntMax() { // HOCON's Config.getInt() throws when a numeric value exceeds int range. diff --git a/framework/src/test/java/org/tron/core/db/HistoryBlockHashIntegrationTest.java b/framework/src/test/java/org/tron/core/db/HistoryBlockHashIntegrationTest.java index be5a012c852..ff2eb5163ae 100644 --- a/framework/src/test/java/org/tron/core/db/HistoryBlockHashIntegrationTest.java +++ b/framework/src/test/java/org/tron/core/db/HistoryBlockHashIntegrationTest.java @@ -57,17 +57,21 @@ public void resetState() { // Storage.commit() translates a zero write into a row delete (see // Storage#commit), so writing ZERO to every slot the suite touches is // the cheapest way to clear leftover state between tests. - Storage storage = new Storage(addr, chainBaseManager.getStorageRowStore()); + Storage storage = openStorage(); for (long slot : new long[]{0L, 99L, 499L, 776L}) { storage.put(new DataWord(slot), DataWord.ZERO()); } storage.commit(); } + private Storage openStorage() { + return new Storage(HistoryBlockHashUtil.HISTORY_STORAGE_ADDRESS, + dbManager.getStorageRowStore(), + dbManager.getDynamicPropertiesStore().allowOptimizeTvmStorage()); + } + private DataWord readSlot(long slot) { - Storage storage = new Storage( - HistoryBlockHashUtil.HISTORY_STORAGE_ADDRESS, - chainBaseManager.getStorageRowStore()); + Storage storage = openStorage(); return storage.getValue(new DataWord(slot)); } @@ -285,9 +289,7 @@ public void generateBlockWritesParentHashBeforeTxLoop() throws Exception { AccountStateCallBack spy = Mockito.spy(realCb); AtomicReference captured = new AtomicReference<>(); Mockito.doAnswer(inv -> { - Storage st = new Storage( - HistoryBlockHashUtil.HISTORY_STORAGE_ADDRESS, - chainBaseManager.getStorageRowStore()); + Storage st = openStorage(); captured.set(st.getValue(new DataWord(expectedSlot))); return inv.callRealMethod(); }).when(spy).executeGenerateFinish(); diff --git a/framework/src/test/java/org/tron/core/db/HistoryBlockHashVmTest.java b/framework/src/test/java/org/tron/core/db/HistoryBlockHashVmTest.java index 2dd15392684..442b7c397f3 100644 --- a/framework/src/test/java/org/tron/core/db/HistoryBlockHashVmTest.java +++ b/framework/src/test/java/org/tron/core/db/HistoryBlockHashVmTest.java @@ -1,6 +1,7 @@ package org.tron.core.db; import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -23,6 +24,7 @@ import org.tron.core.config.args.Args; import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.vm.config.ConfigLoader; +import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.program.Program.IllegalOperationException; import org.tron.core.vm.program.Storage; import org.tron.protos.Protocol; @@ -88,7 +90,7 @@ public void cleanup() { chainBaseManager.getContractStore().delete(addr); chainBaseManager.getAccountStore().delete(addr); - Storage storage = new Storage(addr, chainBaseManager.getStorageRowStore()); + Storage storage = openStorage(); for (long slot : new long[]{0L, 1L, 50L, 100L, 900L, 999L, 1000L}) { storage.put(new DataWord(slot), DataWord.ZERO()); } @@ -96,9 +98,7 @@ public void cleanup() { } private void writeSlot(long slot, byte[] hash) { - Storage storage = new Storage( - HistoryBlockHashUtil.HISTORY_STORAGE_ADDRESS, - chainBaseManager.getStorageRowStore()); + Storage storage = openStorage(); storage.put(new DataWord(slot), new DataWord(hash)); storage.commit(); } @@ -115,6 +115,12 @@ private BlockCapsule blockAt(long num) { return block; } + private Storage openStorage() { + return new Storage(HistoryBlockHashUtil.HISTORY_STORAGE_ADDRESS, + dbManager.getStorageRowStore(), + dbManager.getDynamicPropertiesStore().allowOptimizeTvmStorage()); + } + private static byte[] uint256(long n) { return new DataWord(n).getData(); } @@ -240,4 +246,36 @@ public void vmExecutionDoesNotInvalidOpcodeUnderShanghai() throws Exception { assertFalse("normal read must not revert", result.getRuntime().getResult().isRevert()); } + + @Test + public void writeUsesDatabaseFlagWhenVmConfigIsOff() { + VMConfig.initAllowOptimizeTvmStorage(0); + chainBaseManager.getDynamicPropertiesStore().saveAllowOptimizeTvmStorage(1); + byte[] parent = new byte[32]; + Arrays.fill(parent, (byte) 0x11); + BlockCapsule block = new BlockCapsule( + 1000L, + Sha256Hash.wrap(parent), + System.currentTimeMillis(), + ByteString.copyFrom(new byte[21])); + HistoryBlockHashUtil.write(dbManager, block); + + long slot = 999L; + DataWord expected = new DataWord(parent); + Storage optimized = new Storage( + HistoryBlockHashUtil.HISTORY_STORAGE_ADDRESS, + chainBaseManager.getStorageRowStore(), + true); + Storage legacy = new Storage( + HistoryBlockHashUtil.HISTORY_STORAGE_ADDRESS, + chainBaseManager.getStorageRowStore(), + false); + assertEquals(expected, optimized.getValue(new DataWord(slot))); + assertNull(legacy.getValue(new DataWord(slot))); + assertFalse(VMConfig.allowOptimizeTvmStorage()); + + chainBaseManager.getDynamicPropertiesStore().saveAllowOptimizeTvmStorage(0); + optimized.put(new DataWord(slot), DataWord.ZERO()); + optimized.commit(); + } } diff --git a/framework/src/test/java/org/tron/core/db/ManagerTest.java b/framework/src/test/java/org/tron/core/db/ManagerTest.java index 958a132fbbf..5a903925f19 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -45,10 +45,10 @@ import org.tron.common.logsfilter.EventPluginLoader; import org.tron.common.logsfilter.capsule.BlockFilterCapsule; import org.tron.common.logsfilter.capsule.BlockLogTriggerCapsule; -import org.tron.common.logsfilter.capsule.FilterTriggerCapsule; import org.tron.common.logsfilter.capsule.LogsFilterCapsule; import org.tron.common.logsfilter.capsule.TransactionLogTriggerCapsule; import org.tron.common.logsfilter.capsule.TriggerCapsule; +import org.tron.common.logsfilter.queue.FilterCapsuleQueue; import org.tron.common.logsfilter.trigger.ContractLogTrigger; import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.RuntimeImpl; @@ -1694,8 +1694,8 @@ public void adjustBalance(AccountStore accountStore, byte[] accountAddress, long @Test public void switchForkShouldPostFullNodeFilterForNewBranch() throws Exception { CommonParameter.getInstance().jsonRpcHttpFullNodeEnable = true; - // filterProcessLoop only starts when isJsonRpcFilterEnabled() held at Manager.init() time; it - // was false then, so filterCapsuleQueue is produce-only here and fully observable. + // The consumer thread only starts when isJsonRpcFilterEnabled() held at context startup; it + // was false then, so the FilterCapsuleQueue bean is produce-only here and fully observable. // bootstrap a head with a known witness String key = PublicMethod.getRandomPrivateKey(); @@ -1733,9 +1733,7 @@ public void switchForkShouldPostFullNodeFilterForNewBranch() throws Exception { dbManager.pushBlock(p); long expiration = t + 1_000_000L; - BlockingQueue queue = - ReflectUtils.getFieldValue(dbManager, "filterCapsuleQueue"); - queue.clear(); + FilterCapsuleQueue queue = context.getBean(FilterCapsuleQueue.class); // old branch: A carries a transfer; applied via the normal extend path BlockCapsule a = blockWithTransfer(t + 6000, base + 2, p.getBlockId().getByteString(), keys, @@ -1868,7 +1866,7 @@ private BlockCapsule blockWithTransfer(long time, long number, ByteString parent return blockCapsule; } - private boolean hasLogsFilterCapsule(BlockingQueue queue, BlockCapsule b, + private boolean hasLogsFilterCapsule(FilterCapsuleQueue queue, BlockCapsule b, boolean removed) { String blockHash = b.getBlockId().toString(); return queue.stream() @@ -1878,7 +1876,7 @@ private boolean hasLogsFilterCapsule(BlockingQueue queue, && blockHash.equals(c.getBlockHash())); } - private boolean hasBlockFilterCapsule(BlockingQueue queue, + private boolean hasBlockFilterCapsule(FilterCapsuleQueue queue, BlockCapsule b) { String blockHash = b.getBlockId().toString(); return queue.stream() diff --git a/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java b/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java index e2815e46063..6df63c6c04e 100644 --- a/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java +++ b/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java @@ -125,6 +125,10 @@ public void before() throws IOException { @AfterClass public static void after() throws IOException { + // stopPlugin() is safe when never started: it null-checks pluginManager, and + // NativeMessageQueue.stop() null-checks publisher/context. Ensures the native + // queue socket bound in test() is released even when assertions fail earlier. + EventPluginLoader.getInstance().stopPlugin(); context.destroy(); Args.clearParam(); } @@ -174,7 +178,7 @@ public void test() throws Exception { EventPluginConfig config = new EventPluginConfig(); config.setSendQueueLength(1000); - config.setBindPort(5555); + config.setBindPort(PublicMethod.chooseRandomPort()); config.setUseNativeQueue(true); config.setTriggerConfigList(new ArrayList<>()); diff --git a/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java b/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java index 2fcb624002e..855aae3f22d 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java @@ -23,7 +23,7 @@ @Slf4j public class ConcurrentHashMapTest { private static final String EXECUTOR_NAME = "jsonrpc-concurrent-map-test"; - private final TronJsonRpcImpl jsonRpc = new TronJsonRpcImpl(null, null); + private final TronJsonRpcImpl jsonRpc = new TronJsonRpcImpl(null, null, null); private static int randomInt(int minInt, int maxInt) { return (int) round(random(true) * (maxInt - minInt) + minInt, true); diff --git a/framework/src/test/java/org/tron/core/jsonrpc/FilterPipelineDeliveryTest.java b/framework/src/test/java/org/tron/core/jsonrpc/FilterPipelineDeliveryTest.java new file mode 100644 index 00000000000..df953f34387 --- /dev/null +++ b/framework/src/test/java/org/tron/core/jsonrpc/FilterPipelineDeliveryTest.java @@ -0,0 +1,102 @@ +package org.tron.core.jsonrpc; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.function.BooleanSupplier; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.TestConstants; +import org.tron.common.logsfilter.capsule.BlockFilterCapsule; +import org.tron.common.logsfilter.capsule.LogsFilterCapsule; +import org.tron.common.logsfilter.queue.FilterCapsuleQueue; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.runtime.vm.DataWord; +import org.tron.common.runtime.vm.LogInfo; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.config.args.Args; +import org.tron.core.services.jsonrpc.TronJsonRpc.FilterRequest; +import org.tron.core.services.jsonrpc.TronJsonRpc.LogFilterElement; +import org.tron.core.services.jsonrpc.TronJsonRpcImpl; +import org.tron.core.services.jsonrpc.filters.BlockFilterAndResult; +import org.tron.core.services.jsonrpc.filters.LogFilterAndResult; +import org.tron.protos.Protocol.TransactionInfo; + +/** + * End-to-end coverage of the decoupled filter pipeline: capsules offered to the + * FilterCapsuleQueue bean are delivered to registered filters by the consumer + * thread that TronJsonRpcImpl starts at context startup. + */ +public class FilterPipelineDeliveryTest extends BaseTest { + + static { + Args.setParam(new String[] {"--output-directory", dbPath()}, TestConstants.TEST_CONF); + // isJsonRpcFilterEnabled() must hold at context startup so the consumer thread starts + CommonParameter.getInstance().setJsonRpcHttpFullNodeEnable(true); + } + + @Resource + private TronJsonRpcImpl tronJsonRpc; + @Resource + private FilterCapsuleQueue filterCapsuleQueue; + + private static TransactionInfo buildTxInfoWithLog() { + LogInfo logInfo = new LogInfo(new byte[20], + Collections.singletonList(new DataWord(new byte[32])), new byte[0]); + return TransactionInfo.newBuilder().addLog(LogInfo.buildLog(logInfo)).build(); + } + + private static void await(BooleanSupplier condition, String message) + throws InterruptedException { + long deadline = System.currentTimeMillis() + 10_000; + while (System.currentTimeMillis() < deadline) { + if (condition.getAsBoolean()) { + return; + } + Thread.sleep(50); + } + Assert.fail(message); + } + + @Test + public void consumerStartedWithContext() { + ExecutorService filterEs = ReflectUtils.getFieldValue(tronJsonRpc, "filterEs"); + Assert.assertNotNull("consumer did not start", filterEs); + Assert.assertFalse("consumer already shut down", filterEs.isShutdown()); + } + + @Test + public void blockFilterDeliveredOnFullAndSolidityPaths() throws Exception { + BlockFilterAndResult full = new BlockFilterAndResult(); + BlockFilterAndResult solidity = new BlockFilterAndResult(); + tronJsonRpc.getBlockFilter2ResultFull().put("pipeline-block-full", full); + tronJsonRpc.getBlockFilter2ResultSolidity().put("pipeline-block-solidity", solidity); + try { + filterCapsuleQueue.offer(new BlockFilterCapsule("e2e-full-hash", false)); + filterCapsuleQueue.offer(new BlockFilterCapsule("e2e-solidity-hash", true)); + await(() -> full.getResult().size() == 1, "full-path block hash not delivered"); + await(() -> solidity.getResult().size() == 1, "solidity-path block hash not delivered"); + } finally { + tronJsonRpc.getBlockFilter2ResultFull().remove("pipeline-block-full"); + tronJsonRpc.getBlockFilter2ResultSolidity().remove("pipeline-block-solidity"); + } + } + + @Test + public void reorgLogsDeliveredWithRemovedFlag() throws Exception { + LogFilterAndResult filter = new LogFilterAndResult(new FilterRequest(), 100L, null); + tronJsonRpc.getEventFilter2ResultFull().put("pipeline-log-removed", filter); + try { + filterCapsuleQueue.offer(new LogsFilterCapsule(150L, "0xreorg", null, + Collections.singletonList(buildTxInfoWithLog()), false, true)); + await(() -> !filter.getResult().isEmpty(), "removed log not delivered"); + List elements = filter.popAll(); + Assert.assertEquals(1, elements.size()); + Assert.assertTrue(elements.get(0).isRemoved()); + } finally { + tronJsonRpc.getEventFilter2ResultFull().remove("pipeline-log-removed"); + } + } +} diff --git a/framework/src/test/java/org/tron/core/jsonrpc/FilterPipelineLifecycleTest.java b/framework/src/test/java/org/tron/core/jsonrpc/FilterPipelineLifecycleTest.java new file mode 100644 index 00000000000..3f7407db156 --- /dev/null +++ b/framework/src/test/java/org/tron/core/jsonrpc/FilterPipelineLifecycleTest.java @@ -0,0 +1,288 @@ +package org.tron.core.jsonrpc; + +import com.google.common.util.concurrent.Uninterruptibles; +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import org.junit.After; +import org.junit.Assert; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.tron.common.TestConstants; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.logsfilter.capsule.BlockFilterCapsule; +import org.tron.common.logsfilter.capsule.LogsFilterCapsule; +import org.tron.common.logsfilter.queue.FilterCapsuleQueue; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.services.jsonrpc.TronJsonRpcImpl; +import org.tron.core.services.jsonrpc.filters.LogFilterAndResult; + +/** + * Lifecycle of the filter consumer owned by TronJsonRpcImpl. Only the context-destruction + * case needs Spring; the rest drive a directly constructed instance. + */ +public class FilterPipelineLifecycleTest { + + private static final String FILTER_THREAD = "filter"; + private static final String LOOP_METHOD = "filterProcessLoop"; + // shutdownAndAwaitTermination() escalates to shutdownNow() after 60s; a stop well + // below that bound can only come from the stop flag + private static final long GRACEFUL_BOUND_MS = 10_000; + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private final FilterCapsuleQueue queue = new FilterCapsuleQueue(); + private TronJsonRpcImpl tronJsonRpc; + private Set threadsBeforeStart; + private TronApplicationContext context; + + private void startStandalone(boolean filterEnabled) { + threadsBeforeStart = Thread.getAllStackTraces().keySet(); + CommonParameter.getInstance().setJsonRpcHttpFullNodeEnable(filterEnabled); + CommonParameter.getInstance().setJsonRpcHttpSolidityNodeEnable(false); + tronJsonRpc = new TronJsonRpcImpl(null, null, null); + ReflectUtils.setFieldValue(tronJsonRpc, "filterCapsuleQueue", queue); + ReflectUtils.invokeMethod(tronJsonRpc, "start"); + } + + @After + public void tearDown() { + if (tronJsonRpc != null) { + tronJsonRpc.close(); + } + if (context != null) { + if (context.isActive()) { + context.close(); + } + Args.clearParam(); + } + CommonParameter.getInstance().setJsonRpcHttpFullNodeEnable(false); + CommonParameter.getInstance().setJsonRpcHttpSolidityNodeEnable(false); + } + + private ExecutorService filterEs() { + return ReflectUtils.getFieldValue(tronJsonRpc, "filterEs"); + } + + // only a thread started by this instance, not a consumer leaked by another test + private Optional filterThread() { + return Thread.getAllStackTraces().entrySet().stream() + .filter(e -> !threadsBeforeStart.contains(e.getKey()) + && FILTER_THREAD.equals(e.getKey().getName()) && Arrays.stream(e.getValue()) + .anyMatch(frame -> LOOP_METHOD.equals(frame.getMethodName()))) + .map(Map.Entry::getKey).findFirst(); + } + + private boolean consumerRunning() { + return filterThread().isPresent(); + } + + private static void await(BooleanSupplier condition, String message) + throws InterruptedException { + long deadline = System.currentTimeMillis() + 10_000; + while (System.currentTimeMillis() < deadline) { + if (condition.getAsBoolean()) { + return; + } + Thread.sleep(50); + } + Assert.fail(message); + } + + private static long timedClose(TronJsonRpcImpl rpc) { + long t0 = System.nanoTime(); + rpc.close(); + return (System.nanoTime() - t0) / 1_000_000; + } + + @Test + public void disabledModeStartsNoConsumerAndCloseIsSafe() throws Exception { + startStandalone(false); + Assert.assertNull("consumer started while both filter APIs are disabled", filterEs()); + + tronJsonRpc.close(); + assertPoolsTerminated(); + tronJsonRpc.close(); + assertPoolsTerminated(); + Assert.assertNull(filterEs()); + } + + private void assertPoolsTerminated() { + Assert.assertTrue("logs-filter-pool not terminated", ReflectUtils. + getFieldValue(tronJsonRpc, "logsFilterPool").isTerminated()); + Assert.assertTrue("query-section pool not terminated", ReflectUtils. + getFieldValue(tronJsonRpc, "sectionExecutor").isTerminated()); + } + + /** + * Built like FullNode (circular references disallowed); context.close() is the + * production sequence: ApplicationImpl.shutdown() closes the bean explicitly, then bean + * destruction invokes the inferred close() again. Spring logs rather than propagates a + * failure of that second call, so the consumer state below - not the absence of an + * exception - is what this pins down. + */ + @Test + public void explicitCloseThenContextDestruction() throws Exception { + Args.setParam(new String[] {"--output-directory", + temporaryFolder.newFolder().toString()}, TestConstants.TEST_CONF); + CommonParameter.getInstance().setJsonRpcHttpFullNodeEnable(true); + DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); + beanFactory.setAllowCircularReferences(false); + context = new TronApplicationContext(beanFactory); + context.register(DefaultConfig.class); + context.refresh(); + TronJsonRpcImpl bean = context.getBean(TronJsonRpcImpl.class); + ExecutorService beanFilterEs = ReflectUtils.getFieldValue(bean, "filterEs"); + Assert.assertNotNull("consumer did not start", beanFilterEs); + + context.close(); + Assert.assertTrue("consumer survived context close", beanFilterEs.isTerminated()); + long elapsedMs = timedClose(bean); + Assert.assertTrue("close() after destruction should be harmless and quick, took " + + elapsedMs + "ms", elapsedMs < 1_000); + } + + @Test + public void emptyQueueStopsWithoutForcedCancellation() throws Exception { + startStandalone(true); + await(this::consumerRunning, "consumer did not start"); + + long elapsedMs = timedClose(tronJsonRpc); + Assert.assertTrue("graceful stop took " + elapsedMs + "ms", elapsedMs < GRACEFUL_BOUND_MS); + Assert.assertTrue("consumer still alive after close()", filterEs().isTerminated()); + } + + /** + * Interrupt without close(): the stop flag still says running, so only the + * InterruptedException branch can end the loop. The executor worker outlives the task, + * hence the stack-frame check instead of thread liveness. + */ + @Test + public void interruptDuringPollExitsLoop() throws Exception { + startStandalone(true); + await(this::consumerRunning, "consumer did not start"); + + filterThread().get().interrupt(); + await(() -> !consumerRunning(), "loop kept running after interrupt"); + + queue.offer(new BlockFilterCapsule("0xafter-interrupt", false)); + Thread.sleep(500); + Assert.assertEquals("capsule consumed after the loop exited", 1, queue.stream().count()); + } + + /** + * The closing thread is interrupted while the consumer is mid-capsule: close() gives up + * waiting, keeps the interrupt status and still completes; the consumer is cancelled. + */ + @Test + public void interruptedCloserReturnsAndPreservesInterruptStatus() throws Exception { + startStandalone(true); + + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + queue.offer(new LogsFilterCapsule(150L, "0xblocked", null, + Collections.emptyList(), false, false) { + @Override + public boolean isSolidified() { + entered.countDown(); + try { + release.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return false; + } + }); + Assert.assertTrue("consumer did not pick up the capsule", + entered.await(10, TimeUnit.SECONDS)); + + AtomicBoolean interruptKept = new AtomicBoolean(false); + AtomicReference closeError = new AtomicReference<>(); + Thread closer = new Thread(() -> { + try { + tronJsonRpc.close(); + } catch (Throwable t) { + closeError.set(t); + } finally { + interruptKept.set(Thread.currentThread().isInterrupted()); + } + }, "test-closer"); + closer.start(); + try { + await(filterEs()::isShutdown, "close() did not start stopping the consumer"); + Assert.assertTrue("close() finished while a capsule was in flight", closer.isAlive()); + + closer.interrupt(); + closer.join(GRACEFUL_BOUND_MS); + Assert.assertFalse("interrupted close() did not return", closer.isAlive()); + Assert.assertNull("close() failed", closeError.get()); + Assert.assertTrue("close() swallowed the interrupt status", interruptKept.get()); + + // assert before releasing the latch: a released consumer would finish on its own, + // so only a still-blocked one proves close() cancelled it + Assert.assertTrue("consumer was not cancelled", + filterEs().awaitTermination(10, TimeUnit.SECONDS)); + } finally { + release.countDown(); + } + } + + /** + * Interrupted closer with an over-threshold filter map: the in-flight capsule is handed + * to logsFilterPool, so the pool must outlive the consumer. + */ + @Test + public void interruptedCloserKeepsPoolUntilConsumerExits() throws Exception { + startStandalone(true); + tronJsonRpc.setFilterParallelThreshold(1); + LogFilterAndResult expired = Mockito.mock(LogFilterAndResult.class); + Mockito.when(expired.isExpire()).thenReturn(true); + Map filters = tronJsonRpc.getEventFilter2ResultFull(); + filters.put("0x1", expired); + filters.put("0x2", expired); + + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + queue.offer(new LogsFilterCapsule(150L, "0xblocked", null, + Collections.emptyList(), false, false) { + @Override + public boolean isSolidified() { + entered.countDown(); + Uninterruptibles.awaitUninterruptibly(release); + return false; + } + }); + Assert.assertTrue("consumer did not pick up the capsule", + entered.await(10, TimeUnit.SECONDS)); + + Thread closer = new Thread(tronJsonRpc::close, "test-closer"); + closer.start(); + try { + await(filterEs()::isShutdown, "close() did not start stopping the consumer"); + closer.interrupt(); + // without the fix close() returns here and shuts the pool before the release + closer.join(500); + } finally { + release.countDown(); + } + closer.join(GRACEFUL_BOUND_MS); + Assert.assertFalse("interrupted close() did not return", closer.isAlive()); + Assert.assertTrue("consumer still alive", filterEs().awaitTermination(10, TimeUnit.SECONDS)); + Assert.assertTrue("over-threshold capsule was rejected by a closed pool", filters.isEmpty()); + } +} diff --git a/framework/src/test/java/org/tron/core/jsonrpc/FilterPipelineShutdownTest.java b/framework/src/test/java/org/tron/core/jsonrpc/FilterPipelineShutdownTest.java new file mode 100644 index 00000000000..3630653e717 --- /dev/null +++ b/framework/src/test/java/org/tron/core/jsonrpc/FilterPipelineShutdownTest.java @@ -0,0 +1,108 @@ +package org.tron.core.jsonrpc; + +import java.util.Collections; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.capsule.LogsFilterCapsule; +import org.tron.common.logsfilter.queue.FilterCapsuleQueue; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.runtime.vm.DataWord; +import org.tron.common.runtime.vm.LogInfo; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.services.jsonrpc.TronJsonRpc.FilterRequest; +import org.tron.core.services.jsonrpc.TronJsonRpcImpl; +import org.tron.core.services.jsonrpc.filters.LogFilterAndResult; +import org.tron.protos.Protocol.TransactionInfo; + +/** + * Shutdown semantics of the decoupled filter pipeline, on a directly constructed instance. + */ +public class FilterPipelineShutdownTest { + + private final FilterCapsuleQueue filterCapsuleQueue = new FilterCapsuleQueue(); + private TronJsonRpcImpl tronJsonRpc; + + @Before + public void setUp() { + CommonParameter.getInstance().setJsonRpcHttpFullNodeEnable(true); + tronJsonRpc = new TronJsonRpcImpl(null, null, null); + ReflectUtils.setFieldValue(tronJsonRpc, "filterCapsuleQueue", filterCapsuleQueue); + ReflectUtils.invokeMethod(tronJsonRpc, "start"); + } + + @After + public void tearDown() { + tronJsonRpc.close(); + CommonParameter.getInstance().setJsonRpcHttpFullNodeEnable(false); + } + + private static TransactionInfo buildTxInfoWithLog() { + LogInfo logInfo = new LogInfo(new byte[20], + Collections.singletonList(new DataWord(new byte[32])), new byte[0]); + return TransactionInfo.newBuilder().addLog(LogInfo.buildLog(logInfo)).build(); + } + + /** + * close() while the consumer is mid-capsule on the parallel (logsFilterPool) path: + * the in-flight capsule must complete instead of dying on a RejectedExecutionException, + * which is exactly the filterEs-before-logsFilterPool ordering constraint. A capsule + * queued behind it is not drained. + */ + @Test + public void closeDuringParallelProcessingLosesNoEvent() throws Exception { + tronJsonRpc.setFilterParallelThreshold(0); + LogFilterAndResult filter = new LogFilterAndResult(new FilterRequest(), 100L, null); + tronJsonRpc.getEventFilter2ResultFull().put("shutdown-race", filter); + + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + LogsFilterCapsule capsule = new LogsFilterCapsule(150L, "0xrace", null, + Collections.singletonList(buildTxInfoWithLog()), false, false) { + @Override + public boolean isSolidified() { + // first call is the head of handleLogsFilter, on the consumer thread + entered.countDown(); + try { + release.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return false; + } + }; + filterCapsuleQueue.offer(capsule); + Assert.assertTrue("consumer did not pick up the capsule", + entered.await(10, TimeUnit.SECONDS)); + LogsFilterCapsule queued = new LogsFilterCapsule(151L, "0xqueued", null, + Collections.singletonList(buildTxInfoWithLog()), false, false); + filterCapsuleQueue.offer(queued); + + ExecutorService filterEs = ReflectUtils.getFieldValue(tronJsonRpc, "filterEs"); + Thread closer = new Thread(tronJsonRpc::close, "test-closer"); + closer.start(); + try { + // close() must be parked awaiting the consumer, with logsFilterPool still open + long deadline = System.currentTimeMillis() + 10_000; + while (!filterEs.isShutdown() && System.currentTimeMillis() < deadline) { + Thread.sleep(10); + } + Assert.assertTrue("close() did not start stopping the consumer", filterEs.isShutdown()); + Assert.assertTrue("close() finished while a capsule was in flight", closer.isAlive()); + } finally { + release.countDown(); + } + + closer.join(150_000); + Assert.assertFalse("close() did not finish", closer.isAlive()); + Assert.assertTrue("consumer still running after close()", filterEs.isTerminated()); + Assert.assertEquals("in-flight capsule was lost during close()", + 1, filter.getResult().size()); + Assert.assertTrue("queued capsule was drained during close()", + filterCapsuleQueue.stream().anyMatch(c -> c == queued)); + } +} diff --git a/framework/src/test/java/org/tron/core/jsonrpc/HandleLogsFilterTest.java b/framework/src/test/java/org/tron/core/jsonrpc/HandleLogsFilterTest.java index 33835c482fe..be3098095d5 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/HandleLogsFilterTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/HandleLogsFilterTest.java @@ -27,7 +27,7 @@ public class HandleLogsFilterTest { @Before public void setUp() { - jsonRpc = new TronJsonRpcImpl(null, null); + jsonRpc = new TronJsonRpcImpl(null, null, null); } @After diff --git a/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcCallAndEstimateGasTest.java b/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcCallAndEstimateGasTest.java index 2ab455fa580..cc11b2e99f1 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcCallAndEstimateGasTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcCallAndEstimateGasTest.java @@ -211,8 +211,7 @@ private static TronJsonRpcImpl newRpcWithMockedFailedCall(byte[] resData, Estima }); } - TronJsonRpcImpl rpc = new TronJsonRpcImpl(mockNodeInfo, mockWallet); - rpc.setManager(mockManager); + TronJsonRpcImpl rpc = new TronJsonRpcImpl(mockNodeInfo, mockWallet, mockManager); return rpc; } @@ -239,8 +238,7 @@ private static TronJsonRpcImpl newRpcWithMockedSuccessfulCall(byte[]... constant .build(); }); - TronJsonRpcImpl rpc = new TronJsonRpcImpl(mockNodeInfo, mockWallet); - rpc.setManager(mockManager); + TronJsonRpcImpl rpc = new TronJsonRpcImpl(mockNodeInfo, mockWallet, mockManager); return rpc; } @@ -276,8 +274,7 @@ private static TronJsonRpcImpl newRpcWithMockedEstimateGasSuccessfulCall(long en }); } - TronJsonRpcImpl rpc = new TronJsonRpcImpl(mockNodeInfo, mockWallet); - rpc.setManager(mockManager); + TronJsonRpcImpl rpc = new TronJsonRpcImpl(mockNodeInfo, mockWallet, mockManager); return rpc; } } diff --git a/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java b/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java index e8d14ace060..a564396198d 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java @@ -216,8 +216,7 @@ public void init() { dbManager.getTransactionRetStore() .put(ByteArray.fromLong(blockCapsule2.getNum()), transactionRetCapsule2); - tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet); - tronJsonRpc.setManager(dbManager); + tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, dbManager); } @Test diff --git a/framework/src/test/java/org/tron/core/jsonrpc/WalletCursorTest.java b/framework/src/test/java/org/tron/core/jsonrpc/WalletCursorTest.java index 24ca71a74bc..c26d81e1f99 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/WalletCursorTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/WalletCursorTest.java @@ -60,8 +60,7 @@ public void init() { @Test public void testSource() { - TronJsonRpcImpl tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet); - tronJsonRpc.setManager(dbManager); + TronJsonRpcImpl tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, dbManager); Assert.assertEquals(Cursor.HEAD, wallet.getCursor()); Assert.assertEquals(RequestSource.FULLNODE, tronJsonRpc.getSource()); @@ -92,8 +91,7 @@ public void testDisableInSolidity() { dbManager.setCursor(Cursor.SOLIDITY); - TronJsonRpcImpl tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet); - tronJsonRpc.setManager(dbManager); + TronJsonRpcImpl tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, dbManager); try { tronJsonRpc.buildTransaction(buildArguments); tronJsonRpc.close(); @@ -115,8 +113,7 @@ public void testDisableInPBFT() { dbManager.setCursor(Cursor.PBFT); - TronJsonRpcImpl tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet); - tronJsonRpc.setManager(dbManager); + TronJsonRpcImpl tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, dbManager); try { tronJsonRpc.buildTransaction(buildArguments); } catch (Exception e) { @@ -143,8 +140,7 @@ public void testEnableInFullNode() { buildArguments.setTo("0x548794500882809695a8a687866e76d4271a1abc"); buildArguments.setValue("0x1f4"); - TronJsonRpcImpl tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet); - tronJsonRpc.setManager(dbManager); + TronJsonRpcImpl tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, dbManager); try { tronJsonRpc.buildTransaction(buildArguments); @@ -164,8 +160,7 @@ public void testNewFilter_exceedsCapThrowsException() throws Exception { int saved = Args.getInstance().getJsonRpcMaxLogFilterNum(); Args.getInstance().setJsonRpcMaxLogFilterNum(cap); FilterRequest fr = new FilterRequest(); - TronJsonRpcImpl tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet); - tronJsonRpc.setManager(dbManager); + TronJsonRpcImpl tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, dbManager); Map map = tronJsonRpc.getEventFilter2ResultFull(); List addedKeys = new ArrayList<>(); diff --git a/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java b/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java index f96a03d92e3..07f7bcfc6e8 100644 --- a/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java +++ b/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java @@ -38,6 +38,10 @@ protected void afterInit() { @Test public void testProcessMessage() { + MetricsUtil.getMeter(MetricsKey.NET_TCP_IN_TRAFFIC).mark(1000); + MetricsUtil.getMeter(MetricsKey.NET_TCP_OUT_TRAFFIC).mark(2000); + MetricsUtil.getMeter(MetricsKey.NET_UDP_IN_TRAFFIC).mark(4000); + MetricsUtil.getMeter(MetricsKey.NET_UDP_OUT_TRAFFIC).mark(8000); MetricsInfo m1 = metricsApiService.getMetricsInfo(); @@ -79,6 +83,20 @@ public void testProcessMessage() { Assert.assertEquals(m1.getNet().getErrorProtoCount(), m2.getNet().getErrorProtoCount()); Assert .assertEquals(m1.getNet().getValidConnectionCount(), m2.getNet().getValidConnectionCount()); + + long tcpIn = m1.getNet().getTcpInTraffic().getCount(); + long tcpOut = m1.getNet().getTcpOutTraffic().getCount(); + long udpIn = m1.getNet().getUdpInTraffic().getCount(); + long udpOut = m1.getNet().getUdpOutTraffic().getCount(); + + Assert.assertNotEquals(tcpOut, udpIn); + Assert.assertNotEquals(tcpIn, tcpOut); + Assert.assertNotEquals(udpIn, udpOut); + + Assert.assertEquals(tcpIn, m2.getNet().getTcpInTraffic().getCount()); + Assert.assertEquals(tcpOut, m2.getNet().getTcpOutTraffic().getCount()); + Assert.assertEquals(udpIn, m2.getNet().getUdpInTraffic().getCount()); + Assert.assertEquals(udpOut, m2.getNet().getUdpOutTraffic().getCount()); } } diff --git a/framework/src/test/java/org/tron/core/metrics/prometheus/PrometheusApiServiceTest.java b/framework/src/test/java/org/tron/core/metrics/prometheus/PrometheusApiServiceTest.java index dd260a1b869..4722caec08d 100644 --- a/framework/src/test/java/org/tron/core/metrics/prometheus/PrometheusApiServiceTest.java +++ b/framework/src/test/java/org/tron/core/metrics/prometheus/PrometheusApiServiceTest.java @@ -62,6 +62,7 @@ public class PrometheusApiServiceTest extends BaseTest { Args.setParam(new String[] {"-d", dbPath()}, TestConstants.TEST_CONF); Args.getInstance().setNodeListenPort(10000 + port.incrementAndGet()); initParameter(Args.getInstance()); + Args.getInstance().setMetricsPrometheusPort(PublicMethod.chooseRandomPort()); Metrics.init(); } diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java index be843674632..c8205b6b721 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java @@ -16,6 +16,7 @@ import org.tron.common.ClassLevelAppContextFixture; import org.tron.common.TestConstants; import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.PeerManagerStateResetter; import org.tron.common.utils.ReflectUtils; import org.tron.common.utils.Sha256Hash; import org.tron.consensus.pbft.message.PbftMessage; @@ -45,6 +46,7 @@ public class MessageHandlerTest { @BeforeClass public static void init() throws Exception { + PeerManagerStateResetter.reset(); Args.setParam(new String[] {"--output-directory", temporaryFolder.newFolder().toString(), "--debug"}, TestConstants.TEST_CONF); context = APP_FIXTURE.createContext(); diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java index 65a8f615bfe..15d7107b58f 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java @@ -17,6 +17,7 @@ import org.tron.common.crypto.SignInterface; import org.tron.common.crypto.SignUtils; import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PeerManagerStateResetter; import org.tron.common.utils.PublicMethod; import org.tron.common.utils.ReflectUtils; import org.tron.common.utils.Sha256Hash; @@ -46,6 +47,7 @@ public class PbftMsgHandlerTest { @BeforeClass public static void init() { + PeerManagerStateResetter.reset(); Args.setParam(new String[] {"--output-directory", dbPath, "--debug"}, TestConstants.TEST_CONF); context = new TronApplicationContext(DefaultConfig.class); diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/TransactionsMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/TransactionsMsgHandlerTest.java index ed2121d360f..282c80f9f6d 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/TransactionsMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/TransactionsMsgHandlerTest.java @@ -4,17 +4,19 @@ import com.google.protobuf.ByteString; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; -import lombok.Getter; -import org.joda.time.DateTime; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -23,7 +25,6 @@ import org.tron.common.TestConstants; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ReflectUtils; import org.tron.core.ChainBaseManager; import org.tron.core.config.args.Args; import org.tron.core.exception.P2pException; @@ -48,6 +49,7 @@ public static void init() { @Test public void testProcessMessage() { TransactionsMsgHandler transactionsMsgHandler = new TransactionsMsgHandler(); + ExecutorService originalPool = null; try { transactionsMsgHandler.init(); @@ -67,7 +69,7 @@ public void testProcessMessage() { .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString("121212a9cf"))) .setToAddress(ByteString.copyFrom(ByteArray.fromHexString("232323a9cf"))).build(); - long transactionTimestamp = DateTime.now().minusDays(4).getMillis(); + long transactionTimestamp = ZonedDateTime.now().minusDays(4).toInstant().toEpochMilli(); Protocol.Transaction trx = Protocol.Transaction.newBuilder().setRawData( Protocol.Transaction.raw.newBuilder().setTimestamp(transactionTimestamp) .setRefBlockNum(1) @@ -80,17 +82,29 @@ public void testProcessMessage() { Item item = new Item(new TransactionMessage(trx).getMessageId(), Protocol.Inventory.InventoryType.TRX); advInvRequest.put(item, 0L); + // The non-executing pool must be installed before the first submission so no + // real-pool worker can touch the peer mock while the test re-stubs it (Mockito + // stubbing is not thread-safe). The latch counts down only for off-thread callers, + // which after the replacement is exactly the smart-contract scheduler. + CountDownLatch smartContractSubmitted = new CountDownLatch(1); + Thread testThread = Thread.currentThread(); + ExecutorService mockPool = Mockito.mock(ExecutorService.class); + Future submittedTask = Mockito.mock(Future.class); + Mockito.when(mockPool.submit(Mockito.any(Runnable.class))).thenAnswer(invocation -> { + if (Thread.currentThread() != testThread) { + smartContractSubmitted.countDown(); + } + return submittedTask; + }); + originalPool = replaceTrxHandlePool(transactionsMsgHandler, mockPool); + Mockito.when(peer.getAdvInvRequest()).thenReturn(advInvRequest); List transactionList = new ArrayList<>(); transactionList.add(trx); transactionsMsgHandler.processMessage(peer, new TransactionsMessage(transactionList)); Assert.assertNull(advInvRequest.get(item)); - //Thread.sleep(10); - BlockingQueue smartContractQueue = - new LinkedBlockingQueue(2); - smartContractQueue.offer(new TrxEvent(null, null)); - smartContractQueue.offer(new TrxEvent(null, null)); + BlockingQueue smartContractQueue = new LinkedBlockingQueue<>(1); Field field1 = TransactionsMsgHandler.class.getDeclaredField("smartContractQueue"); field1.setAccessible(true); field1.set(transactionsMsgHandler, smartContractQueue); @@ -99,15 +113,27 @@ public void testProcessMessage() { ByteArray.fromHexString("121212a9cf"), ByteArray.fromHexString("123456"), 100, 100000000, 0, 0); + Protocol.Transaction trx3 = TvmTestUtils.generateTriggerSmartContractAndGetTransaction( + ByteArray.fromHexString("121212a9cf"), + ByteArray.fromHexString("121212a9cf"), + ByteArray.fromHexString("123457"), + 100, 100000000, 0, 0); Map advInvRequest1 = new ConcurrentHashMap<>(); Item item1 = new Item(new TransactionMessage(trx1).getMessageId(), Protocol.Inventory.InventoryType.TRX); advInvRequest1.put(item1, 0L); + Item item3 = new Item(new TransactionMessage(trx3).getMessageId(), + Protocol.Inventory.InventoryType.TRX); + advInvRequest1.put(item3, 0L); Mockito.when(peer.getAdvInvRequest()).thenReturn(advInvRequest1); List transactionList1 = new ArrayList<>(); transactionList1.add(trx1); + transactionList1.add(trx3); transactionsMsgHandler.processMessage(peer, new TransactionsMessage(transactionList1)); - Assert.assertNull(advInvRequest.get(item1)); + Assert.assertNull(advInvRequest1.get(item1)); + Assert.assertNull(advInvRequest1.get(item3)); + Assert.assertTrue("smart-contract scheduler did not submit work", + smartContractSubmitted.await(3, TimeUnit.SECONDS)); // test 0 contract Protocol.Transaction trx2 = Protocol.Transaction.newBuilder().setRawData( @@ -132,37 +158,40 @@ public void testProcessMessage() { Assert.assertTrue(true); } } catch (Exception e) { - Assert.fail(); + Assert.fail(e.getMessage()); } finally { - transactionsMsgHandler.close(); + closeHandlerAndOriginalPool(transactionsMsgHandler, originalPool); } } @Test public void testProcessMessageAfterClose() throws Exception { TransactionsMsgHandler handler = new TransactionsMsgHandler(); - handler.init(); - handler.close(); + try { + handler.init(); + handler.close(); - PeerConnection peer = Mockito.mock(PeerConnection.class); - TransactionsMessage msg = Mockito.mock(TransactionsMessage.class); + PeerConnection peer = Mockito.mock(PeerConnection.class); + TransactionsMessage msg = Mockito.mock(TransactionsMessage.class); - handler.processMessage(peer, msg); + handler.processMessage(peer, msg); - Mockito.verify(msg, Mockito.never()).getTransactions(); - Mockito.verifyNoInteractions(peer); + Mockito.verify(msg, Mockito.never()).getTransactions(); + Mockito.verifyNoInteractions(peer); + } finally { + handler.close(); + } } @Test public void testRejectedExecution() throws Exception { TransactionsMsgHandler handler = new TransactionsMsgHandler(); + ExecutorService originalPool = null; try { ExecutorService mockPool = Mockito.mock(ExecutorService.class); Mockito.when(mockPool.submit(Mockito.any(Runnable.class))) .thenThrow(new RejectedExecutionException("pool closed")); - Field poolField = TransactionsMsgHandler.class.getDeclaredField("trxHandlePool"); - poolField.setAccessible(true); - poolField.set(handler, mockPool); + originalPool = replaceTrxHandlePool(handler, mockPool); PeerConnection peer = Mockito.mock(PeerConnection.class); TransactionsMessage msg = buildTransferMessage(2); @@ -172,26 +201,26 @@ public void testRejectedExecution() throws Exception { Mockito.verify(mockPool, Mockito.times(1)).submit(Mockito.any(Runnable.class)); } finally { - handler.close(); + closeHandlerAndOriginalPool(handler, originalPool); } } @Test public void testCloseDuringProcessing() throws Exception { TransactionsMsgHandler handler = new TransactionsMsgHandler(); + ExecutorService originalPool = null; try { Field closedField = TransactionsMsgHandler.class.getDeclaredField("isClosed"); closedField.setAccessible(true); ExecutorService mockPool = Mockito.mock(ExecutorService.class); + Future submittedTask = Mockito.mock(Future.class); // on the first submit, flip isClosed to true so the second iteration breaks Mockito.when(mockPool.submit(Mockito.any(Runnable.class))).thenAnswer(inv -> { closedField.set(handler, true); - return null; + return submittedTask; }); - Field poolField = TransactionsMsgHandler.class.getDeclaredField("trxHandlePool"); - poolField.setAccessible(true); - poolField.set(handler, mockPool); + originalPool = replaceTrxHandlePool(handler, mockPool); PeerConnection peer = Mockito.mock(PeerConnection.class); TransactionsMessage msg = buildTransferMessage(2); @@ -200,7 +229,7 @@ public void testCloseDuringProcessing() throws Exception { Mockito.verify(mockPool, Mockito.times(1)).submit(Mockito.any(Runnable.class)); } finally { - handler.close(); + closeHandlerAndOriginalPool(handler, originalPool); } } @@ -234,6 +263,34 @@ private void stubAdvInvRequest(PeerConnection peer, TransactionsMessage msg) { Mockito.when(peer.getAdvInvRequest()).thenReturn(advInvRequest); } + private ExecutorService replaceTrxHandlePool(TransactionsMsgHandler handler, ExecutorService pool) + throws Exception { + Field poolField = TransactionsMsgHandler.class.getDeclaredField("trxHandlePool"); + poolField.setAccessible(true); + ExecutorService originalPool = (ExecutorService) poolField.get(handler); + poolField.set(handler, pool); + return originalPool; + } + + private void closeHandlerAndOriginalPool(TransactionsMsgHandler handler, + ExecutorService originalPool) { + try { + handler.close(); + } finally { + if (originalPool != null) { + originalPool.shutdown(); + try { + if (!originalPool.awaitTermination(5, TimeUnit.SECONDS)) { + originalPool.shutdownNow(); + } + } catch (InterruptedException e) { + originalPool.shutdownNow(); + Thread.currentThread().interrupt(); + } + } + } + } + @Test public void testHandleTransaction() throws Exception { TransactionsMsgHandler handler = new TransactionsMsgHandler(); @@ -341,7 +398,20 @@ public void testDuplicateTransactionRejected() throws Exception { public void testInvalidSigLength() throws Exception { TransactionsMsgHandler handler = new TransactionsMsgHandler(); handler.init(); + ExecutorService originalPool = null; try { + // Mock pool never executes submitted tasks: the async worker would invoke isBadPeer() + // on the stubbed peer concurrently with main-thread re-stubbing of getAdvInvRequest(), + // and Mockito's per-mock invocationForStubbing state is not thread-safe + // (intermittent WrongTypeOfReturnValue: ConcurrentHashMap cannot be returned by + // isBadPeer()). This test only asserts the synchronous check() length validation, + // so not running the worker is intentional. + ExecutorService mockPool = Mockito.mock(ExecutorService.class); + Future submittedTask = Mockito.mock(Future.class); + Mockito.when(mockPool.submit(Mockito.any(Runnable.class))) + .thenAnswer(invocation -> submittedTask); + originalPool = replaceTrxHandlePool(handler, mockPool); + PeerConnection peer = Mockito.mock(PeerConnection.class); BalanceContract.TransferContract transferContract = BalanceContract.TransferContract @@ -418,45 +488,32 @@ public void testInvalidSigLength() throws Exception { stubAdvInvRequest(peer, new TransactionsMessage(paddedList)); handler.processMessage(peer, new TransactionsMessage(paddedList)); } finally { - handler.close(); + closeHandlerAndOriginalPool(handler, originalPool); } } @Test public void testIsBusyWithCachedTransactions() throws Exception { TransactionsMsgHandler handler = new TransactionsMsgHandler(); + try { + int threshold = Args.getInstance().getMaxTrxCacheSize(); + TronNetDelegate tronNetDelegateMock = Mockito.mock(TronNetDelegate.class); + Field field = TransactionsMsgHandler.class.getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(handler, tronNetDelegateMock); - int threshold = Args.getInstance().getMaxTrxCacheSize(); - TronNetDelegate tronNetDelegateMock = Mockito.mock(TronNetDelegate.class); - Field field = TransactionsMsgHandler.class.getDeclaredField("tronNetDelegate"); - field.setAccessible(true); - field.set(handler, tronNetDelegateMock); - - // queue and smartContractQueue are empty, but cached size > threshold - Mockito.when(tronNetDelegateMock.getCachedTransactionSize()).thenReturn(threshold + 1); - Assert.assertTrue(handler.isBusy()); - - // boundary: cached size == threshold, isBusy() uses strict >, so not busy - Mockito.when(tronNetDelegateMock.getCachedTransactionSize()).thenReturn(threshold); - Assert.assertFalse(handler.isBusy()); - - Mockito.when(tronNetDelegateMock.getCachedTransactionSize()).thenReturn(0); - Assert.assertFalse(handler.isBusy()); - } - - class TrxEvent { + // queue and smartContractQueue are empty, but cached size > threshold + Mockito.when(tronNetDelegateMock.getCachedTransactionSize()).thenReturn(threshold + 1); + Assert.assertTrue(handler.isBusy()); - @Getter - private PeerConnection peer; - @Getter - private TransactionMessage msg; - @Getter - private long time; + // boundary: cached size == threshold, isBusy() uses strict >, so not busy + Mockito.when(tronNetDelegateMock.getCachedTransactionSize()).thenReturn(threshold); + Assert.assertFalse(handler.isBusy()); - public TrxEvent(PeerConnection peer, TransactionMessage msg) { - this.peer = peer; - this.msg = msg; - this.time = System.currentTimeMillis(); + Mockito.when(tronNetDelegateMock.getCachedTransactionSize()).thenReturn(0); + Assert.assertFalse(handler.isBusy()); + } finally { + handler.close(); } } } diff --git a/framework/src/test/java/org/tron/core/net/peer/PeerManagerTest.java b/framework/src/test/java/org/tron/core/net/peer/PeerManagerTest.java index ffba127a6fd..16e88b38584 100644 --- a/framework/src/test/java/org/tron/core/net/peer/PeerManagerTest.java +++ b/framework/src/test/java/org/tron/core/net/peer/PeerManagerTest.java @@ -17,6 +17,7 @@ import org.springframework.context.ApplicationContext; import org.tron.common.TestConstants; import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.PeerManagerStateResetter; import org.tron.common.utils.ReflectUtils; import org.tron.core.config.args.Args; import org.tron.p2p.connection.Channel; @@ -25,6 +26,7 @@ public class PeerManagerTest { @BeforeClass public static void initArgs() { + PeerManagerStateResetter.reset(); Args.setParam(new String[]{}, TestConstants.TEST_CONF); CommonParameter.getInstance().setRateLimiterSyncBlockChain(10); CommonParameter.getInstance().setRateLimiterFetchInvData(10); diff --git a/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java b/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java index b8b0d5f6deb..dce5ccb851f 100644 --- a/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java +++ b/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java @@ -19,6 +19,7 @@ import org.springframework.context.ApplicationContext; import org.tron.common.TestConstants; import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.PeerManagerStateResetter; import org.tron.common.utils.ReflectUtils; import org.tron.common.utils.Sha256Hash; import org.tron.core.ChainBaseManager; @@ -52,6 +53,7 @@ public class HandShakeServiceTest { @BeforeClass public static void init() throws Exception { + PeerManagerStateResetter.reset(); Args.setParam(new String[] {"--output-directory", temporaryFolder.newFolder().toString(), "--debug"}, TestConstants.TEST_CONF); context = new TronApplicationContext(DefaultConfig.class); diff --git a/framework/src/test/java/org/tron/core/services/RpcApiServiceErrorPathTest.java b/framework/src/test/java/org/tron/core/services/RpcApiServiceErrorPathTest.java new file mode 100644 index 00000000000..16437f139e7 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/RpcApiServiceErrorPathTest.java @@ -0,0 +1,140 @@ +package org.tron.core.services; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.withSettings; + +import com.google.protobuf.Message; +import io.grpc.stub.StreamObserver; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Answers; +import org.mockito.stubbing.Answer; +import org.tron.core.Wallet; +import org.tron.core.metrics.MetricsApiService; +import org.tron.core.services.RpcApiService.WalletApi; +import org.tron.core.services.RpcApiService.WalletSolidityApi; +import org.tron.core.utils.TransactionUtil; + +/** + * Pins the one-terminal-event rule on the gRPC error path: a handler that reports a failure through + * {@code onError} must not fall through to {@code onCompleted}. gRPC rejects the second close with + * {@code IllegalStateException("call already closed")}, so a handler doing both costs a server-side + * exception on every failed call while the client sees nothing extra. + * + *

    The rule is checked for every handler rather than for the ones that were fixed, because the + * shape is trivially reintroduced by copying a neighbouring handler. + */ +public class RpcApiServiceErrorPathTest { + + /** Minimum handlers that must actually fail, so the sweep cannot silently cover nothing. */ + private static final int MIN_EXERCISED = 20; + + @Test + public void testWalletApiTerminatesTheCallOnce() throws Exception { + assertSingleTerminalEvent(WalletApi.class); + } + + @Test + public void testWalletSolidityApiTerminatesTheCallOnce() throws Exception { + assertSingleTerminalEvent(WalletSolidityApi.class); + } + + /** + * Drives every unary handler of the given service class with collaborators that throw, and + * asserts none of them terminates the call more than once. + */ + private static void assertSingleTerminalEvent(Class apiClass) throws Exception { + RpcApiService service = mock(RpcApiService.class, + withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); + injectThrowingCollaborators(service); + Object api = apiClass.getDeclaredConstructor(RpcApiService.class).newInstance(service); + + int exercised = 0; + for (Method method : apiClass.getDeclaredMethods()) { + if (!isUnaryHandler(method)) { + continue; + } + Message request = (Message) method.getParameterTypes()[0] + .getMethod("getDefaultInstance").invoke(null); + TerminalRecorder recorder = new TerminalRecorder(); + try { + method.invoke(api, request, recorder); + } catch (InvocationTargetException e) { + // a handler that lets the failure escape cannot have closed the call twice + continue; + } + Assert.assertTrue( + method.getName() + " terminated the call " + recorder.events.size() + " times " + + recorder.events + "; onError must be followed by return", + recorder.events.size() <= 1); + if (!recorder.events.isEmpty()) { + exercised++; + } + } + Assert.assertTrue( + apiClass.getSimpleName() + " exercised only " + exercised + " handlers, expected at least " + + MIN_EXERCISED + " — the sweep is no longer reaching the handler bodies", + exercised >= MIN_EXERCISED); + } + + private static boolean isUnaryHandler(Method method) { + Class[] params = method.getParameterTypes(); + return Modifier.isPublic(method.getModifiers()) + && method.getReturnType() == void.class + && params.length == 2 + && Message.class.isAssignableFrom(params[0]) + && params[1] == StreamObserver.class; + } + + /** + * Replaces the service's collaborators with mocks that throw on every call, so each handler takes + * its own error path, and binds a real {@code WalletApi} for the solidity handlers to delegate + * to. + */ + private static void injectThrowingCollaborators(RpcApiService service) throws Exception { + Answer throwing = invocation -> { + throw new RuntimeException("collaborator unavailable"); + }; + set(service, "wallet", mock(Wallet.class, withSettings().defaultAnswer(throwing))); + set(service, "transactionUtil", + mock(TransactionUtil.class, withSettings().defaultAnswer(throwing))); + set(service, "nodeInfoService", + mock(NodeInfoService.class, withSettings().defaultAnswer(throwing))); + set(service, "metricsApiService", + mock(MetricsApiService.class, withSettings().defaultAnswer(throwing))); + set(service, "walletApi", + WalletApi.class.getDeclaredConstructor(RpcApiService.class).newInstance(service)); + } + + private static void set(RpcApiService service, String name, Object value) throws Exception { + Field field = RpcApiService.class.getDeclaredField(name); + field.setAccessible(true); + field.set(service, value); + } + + /** Counts terminal events instead of closing a real call. */ + private static final class TerminalRecorder implements StreamObserver { + + private final List events = new ArrayList<>(); + + @Override + public void onNext(Object value) { + } + + @Override + public void onError(Throwable t) { + events.add("onError"); + } + + @Override + public void onCompleted() { + events.add("onCompleted"); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/RpcApiServiceLegacyWalletExtensionTest.java b/framework/src/test/java/org/tron/core/services/RpcApiServiceLegacyWalletExtensionTest.java new file mode 100644 index 00000000000..0ac933ff3b6 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/RpcApiServiceLegacyWalletExtensionTest.java @@ -0,0 +1,95 @@ +package org.tron.core.services; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.google.protobuf.Empty; +import com.typesafe.config.ConfigFactory; +import io.grpc.CallOptions; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.MethodDescriptor; +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.NettyServerBuilder; +import io.grpc.protobuf.ProtoUtils; +import io.grpc.stub.ClientCalls; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.tron.api.DatabaseGrpc; +import org.tron.api.WalletSolidityGrpc; +import org.tron.core.config.args.Args; + +public class RpcApiServiceLegacyWalletExtensionTest { + + private static final String LEGACY_SERVICE = "protocol.WalletExtension"; + private static final String[] LEGACY_METHODS = { + "GetTransactionsFromThis", "GetTransactionsFromThis2", + "GetTransactionsToThis", "GetTransactionsToThis2"}; + + private Server server; + private ManagedChannel channel; + + @Before + public void setUp() throws IOException { + Args.applyConfigParams(ConfigFactory.parseString("node { walletExtensionApi = true }") + .withFallback(ConfigFactory.defaultReference())); + Args.getInstance().setSolidityNode(true); + + NettyServerBuilder builder = NettyServerBuilder.forPort(0); + new RpcApiService().addService(builder); + server = builder.build().start(); + channel = ManagedChannelBuilder.forAddress("127.0.0.1", server.getPort()) + .usePlaintext() + .build(); + } + + @After + public void tearDown() throws InterruptedException { + try { + if (channel != null) { + channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + if (server != null) { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } finally { + Args.clearParam(); + } + } + + @Test + public void testSolidityNodeDoesNotRegisterWalletExtension() { + List services = server.getServices().stream() + .map(s -> s.getServiceDescriptor().getName()) + .collect(Collectors.toList()); + assertTrue(services.contains(WalletSolidityGrpc.SERVICE_NAME)); + assertTrue(services.contains(DatabaseGrpc.SERVICE_NAME)); + assertFalse(services.contains(LEGACY_SERVICE)); + } + + @Test + public void testLegacyMethodsReturnUnimplemented() { + for (String name : LEGACY_METHODS) { + MethodDescriptor method = MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(MethodDescriptor.generateFullMethodName(LEGACY_SERVICE, name)) + .setRequestMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + StatusRuntimeException e = assertThrows(StatusRuntimeException.class, + () -> ClientCalls.blockingUnaryCall(channel, method, + CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS), + Empty.getDefaultInstance())); + assertEquals(name, Status.Code.UNIMPLEMENTED, e.getStatus().getCode()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java index c3ac5800971..3df54b9c0f9 100644 --- a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java +++ b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java @@ -277,6 +277,7 @@ public void testGetPaginatedNowWitnessList() { .setOffset(0).setLimit(5).build(); assertNotNull(blockingStubFull.getPaginatedNowWitnessList(paginatedMessage)); assertNotNull(blockingStubSolidity.getPaginatedNowWitnessList(paginatedMessage)); + assertNotNull(blockingStubPBFT.getPaginatedNowWitnessList(paginatedMessage)); } @Test @@ -673,6 +674,7 @@ public void testGetTransactionInfoByBlockNum() { NumberMessage message = NumberMessage.newBuilder().setNum(1).build(); assertNotNull(blockingStubFull.getTransactionInfoByBlockNum(message)); assertNotNull(blockingStubSolidity.getTransactionInfoByBlockNum(message)); + assertNotNull(blockingStubPBFT.getTransactionInfoByBlockNum(message)); } @Test diff --git a/framework/src/test/java/org/tron/core/services/WalletApiTest.java b/framework/src/test/java/org/tron/core/services/WalletApiTest.java index 4a55556afb1..25b21f30872 100644 --- a/framework/src/test/java/org/tron/core/services/WalletApiTest.java +++ b/framework/src/test/java/org/tron/core/services/WalletApiTest.java @@ -17,6 +17,7 @@ import org.tron.common.ClassLevelAppContextFixture; import org.tron.common.TestConstants; import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.PeerManagerStateResetter; import org.tron.common.utils.PublicMethod; import org.tron.common.utils.TimeoutInterceptor; import org.tron.core.config.args.Args; @@ -38,6 +39,7 @@ public class WalletApiTest { @BeforeClass public static void init() throws IOException { + PeerManagerStateResetter.reset(); Args.setParam(new String[] {"-d", temporaryFolder.newFolder().toString(), "--p2p-disable", "true"}, TestConstants.TEST_CONF); Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort()); diff --git a/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorScopeTest.java b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorScopeTest.java new file mode 100644 index 00000000000..d1e01693fd6 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorScopeTest.java @@ -0,0 +1,145 @@ +package org.tron.core.services.filter; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; + +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import java.lang.reflect.Field; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.core.db.Manager; +import org.tron.core.db2.core.Chainbase; + +/** + * Pins the cursor's scope without depending on thread-pool scheduling. + * + *

    {@code interceptCall()} is driven on thread A and the returned listener's + * {@code onHalfClose()} on a different thread B, which is what gRPC's {@code SerializingExecutor} + * is free to do. An implementation that scoped the cursor around {@code interceptCall} instead of + * {@code onHalfClose} then fails here by construction rather than by luck. + */ +public class CursorInterceptorScopeTest { + + private ExecutorService threadA; + private ExecutorService threadB; + + private Manager manager; + private Chainbase.Cursor cursorDuringHandler; + private Chainbase.Cursor cursorOnThreadAAfterInterceptCall; + + /** Per-thread cursor, like the ThreadLocal in Chainbase; HEAD when nothing is set. */ + private final ThreadLocal cursor = + ThreadLocal.withInitial(() -> Chainbase.Cursor.HEAD); + + @Before + public void setUp() { + threadA = Executors.newSingleThreadExecutor(r -> new Thread(r, "cursor-thread-A")); + threadB = Executors.newSingleThreadExecutor(r -> new Thread(r, "cursor-thread-B")); + + manager = mock(Manager.class); + doAnswer(inv -> { + cursor.set(inv.getArgument(0)); + return null; + }).when(manager).setCursor(any(Chainbase.Cursor.class)); + doAnswer(inv -> { + cursor.set(Chainbase.Cursor.HEAD); + return null; + }).when(manager).resetCursor(); + } + + @After + public void tearDown() throws Exception { + threadA.shutdownNow(); + threadB.shutdownNow(); + threadA.awaitTermination(5, TimeUnit.SECONDS); + threadB.awaitTermination(5, TimeUnit.SECONDS); + } + + @Test + public void testHandlerSeesTheCursorWhenInterceptCallRanOnAnotherThread() throws Exception { + ServerCall.Listener listener = startCallOnThreadA(false); + + // the handler runs from onHalfClose, on a different thread than interceptCall + Chainbase.Cursor cursorOnThreadBAfterHalfClose = runOn(threadB, () -> { + listener.onHalfClose(); + return cursor.get(); + }); + + Assert.assertEquals("interceptCall must not select the cursor on its own thread", + Chainbase.Cursor.HEAD, cursorOnThreadAAfterInterceptCall); + Assert.assertEquals("handler must observe the SOLIDITY cursor", + Chainbase.Cursor.SOLIDITY, cursorDuringHandler); + Assert.assertEquals("cursor must be back at HEAD on the handler thread once it returns", + Chainbase.Cursor.HEAD, cursorOnThreadBAfterHalfClose); + } + + @Test + public void testCursorIsRestoredOnThreadBWhenTheHandlerThrows() throws Exception { + ServerCall.Listener listener = startCallOnThreadA(true); + + try { + runOn(threadB, () -> { + listener.onHalfClose(); + return null; + }); + Assert.fail("expected the handler failure to propagate"); + } catch (Exception expected) { + // what matters is the cursor state below + } + + // threadB is a single thread, so this reads the cursor of the thread the handler threw on + Assert.assertEquals("a throwing handler must still leave the cursor at HEAD", + Chainbase.Cursor.HEAD, runOn(threadB, cursor::get)); + } + + /** Runs interceptCall on thread A and returns the listener, with a handler that records state. */ + private ServerCall.Listener startCallOnThreadA(boolean handlerThrows) throws Exception { + SolidityCursorInterceptor interceptor = new SolidityCursorInterceptor(); + Field dbManager = CursorServerInterceptor.class.getDeclaredField("dbManager"); + dbManager.setAccessible(true); + dbManager.set(interceptor, manager); + + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + @SuppressWarnings("unchecked") + MethodDescriptor descriptor = mock(MethodDescriptor.class); + doAnswer(inv -> descriptor).when(call).getMethodDescriptor(); + + ServerCallHandler handler = (c, h) -> new ServerCall.Listener() { + @Override + public void onHalfClose() { + cursorDuringHandler = cursor.get(); + if (handlerThrows) { + throw new IllegalStateException("boom"); + } + } + }; + + return runOn(threadA, () -> { + ServerCall.Listener l = interceptor.interceptCall(call, new Metadata(), handler); + cursorOnThreadAAfterInterceptCall = cursor.get(); + return l; + }); + } + + private static T runOn(ExecutorService executor, Callable task) throws Exception { + try { + return executor.submit(task).get(5, TimeUnit.SECONDS); + } catch (java.util.concurrent.ExecutionException e) { + if (e.getCause() instanceof Exception) { + throw (Exception) e.getCause(); + } + throw e; + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorServerTest.java b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorServerTest.java new file mode 100644 index 00000000000..5e58e3d7bcc --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorServerTest.java @@ -0,0 +1,131 @@ +package org.tron.core.services.filter; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.Server; +import io.grpc.ServerBuilder; +import io.grpc.stub.StreamObserver; +import java.lang.reflect.Field; +import java.net.ServerSocket; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.api.DatabaseGrpc; +import org.tron.api.DatabaseGrpc.DatabaseImplBase; +import org.tron.api.GrpcAPI.EmptyMessage; +import org.tron.core.db.Manager; +import org.tron.core.db2.core.Chainbase; +import org.tron.protos.Protocol.Block; + +/** + * Drives the production interceptor through a real gRPC server, which is the only place the + * assumption it rests on can be checked: that gRPC runs the handler inline from + * {@code onHalfClose}, on the same thread. The cursor is a {@link ThreadLocal}, so if that stops + * holding the cursor never reaches the read path and the port serves HEAD data with no error — + * responses stay well-formed, so nothing else notices. + * + *

    CursorInterceptorScopeTest covers the interceptor's own logic on a synthetic harness; this is + * the end-to-end half. + */ +public class CursorInterceptorServerTest { + + private ExecutorService executor; + + @Before + public void setUp() { + // a fixed thread pool mirrors the production server configuration + executor = Executors.newFixedThreadPool(2, r -> { + Thread thread = new Thread(r); + thread.setName("cursor-rpc-executor-" + thread.getId()); + return thread; + }); + } + + @After + public void tearDown() throws Exception { + if (executor != null) { + executor.shutdown(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + executor.shutdownNow(); + } + } + } + + @Test + public void testCursorIsSetAndRestoredOnTheHandlerThread() throws Exception { + final List setOn = new CopyOnWriteArrayList<>(); + final List resetOn = new CopyOnWriteArrayList<>(); + final String[] handlerOn = new String[1]; + // the client can receive the response before the server leaves onHalfClose's finally block + final CountDownLatch resetDone = new CountDownLatch(1); + + Manager manager = mock(Manager.class); + doAnswer(inv -> setOn.add(Thread.currentThread().getName())) + .when(manager).setCursor(any(Chainbase.Cursor.class)); + doAnswer(inv -> { + resetOn.add(Thread.currentThread().getName()); + resetDone.countDown(); + return null; + }).when(manager).resetCursor(); + + SolidityCursorInterceptor interceptor = new SolidityCursorInterceptor(); + Field dbManager = CursorServerInterceptor.class.getDeclaredField("dbManager"); + dbManager.setAccessible(true); + dbManager.set(interceptor, manager); + + int port = freePort(); + Server server = ServerBuilder.forPort(port) + .executor(executor) + .addService(new DatabaseImplBase() { + @Override + public void getNowBlock(EmptyMessage request, StreamObserver observer) { + handlerOn[0] = Thread.currentThread().getName(); + observer.onNext(Block.getDefaultInstance()); + observer.onCompleted(); + } + }) + .intercept(interceptor) + .build() + .start(); + + ManagedChannel channel = ManagedChannelBuilder.forAddress("127.0.0.1", port) + .usePlaintext().directExecutor().build(); + try { + DatabaseGrpc.newBlockingStub(channel).getNowBlock(EmptyMessage.getDefaultInstance()); + + Assert.assertTrue("cursor was not restored after the call", + resetDone.await(5, TimeUnit.SECONDS)); + Assert.assertEquals("cursor must be set exactly once per call", 1, setOn.size()); + Assert.assertEquals("cursor must be restored exactly once per call", 1, resetOn.size()); + Assert.assertNotNull("handler did not run", handlerOn[0]); + // the ThreadLocal cursor only reaches the read path if it is set on the handler's thread + Assert.assertEquals("cursor was set on a thread other than the handler's", + handlerOn[0], setOn.get(0)); + Assert.assertEquals("cursor was restored on a thread other than the handler's", + handlerOn[0], resetOn.get(0)); + verify(manager).setCursor(Chainbase.Cursor.SOLIDITY); + } finally { + channel.shutdownNow(); + server.shutdownNow(); + server.awaitTermination(5, TimeUnit.SECONDS); + } + } + + private static int freePort() throws Exception { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorWiringTest.java b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorWiringTest.java new file mode 100644 index 00000000000..5f403b9d742 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/filter/CursorInterceptorWiringTest.java @@ -0,0 +1,101 @@ +package org.tron.core.services.filter; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.withSettings; + +import io.grpc.BindableService; +import io.grpc.ServerServiceDefinition; +import io.grpc.netty.NettyServerBuilder; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Answers; +import org.mockito.ArgumentCaptor; +import org.tron.api.DatabaseGrpc; +import org.tron.api.WalletSolidityGrpc; +import org.tron.core.services.RpcApiService; +import org.tron.core.services.interfaceOnPBFT.RpcApiServiceOnPBFT; +import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity; + +/** + * Guards that each cursor gRPC service registers the shared read services through its + * cursor interceptor. Nothing else catches a dropped interceptor: the services would still be + * served and every response would still look well-formed, only resolved against HEAD instead of the + * solidified or PBFT snapshot. This is the gRPC counterpart of CursorFilterInstallationTest. + * + *

    Registering without the interceptor binds the {@code addService(BindableService)} overload + * rather than the {@code addService(ServerServiceDefinition)} one, so the two are distinguishable + * here. What the interceptor does once attached is pinned by CursorInterceptorScopeTest and + * CursorInterceptorServerTest. + */ +public class CursorInterceptorWiringTest { + + private static final Set SHARED_READ_SERVICES = new HashSet<>( + Arrays.asList(DatabaseGrpc.SERVICE_NAME, WalletSolidityGrpc.SERVICE_NAME)); + + @Test + public void testSolidityServiceRegistersBothReadServicesThroughTheCursor() throws Exception { + Assert.assertEquals(SHARED_READ_SERVICES, + interceptedServices(RpcApiServiceOnSolidity.class, new SolidityCursorInterceptor())); + } + + @Test + public void testPbftServiceRegistersBothReadServicesThroughTheCursor() throws Exception { + Assert.assertEquals(SHARED_READ_SERVICES, + interceptedServices(RpcApiServiceOnPBFT.class, new PbftCursorInterceptor())); + } + + /** + * Runs the service's real addService against a mock builder and returns the names of the services + * it registered as intercepted definitions, failing if any was registered unintercepted. + */ + private static Set interceptedServices(Class serviceClass, + CursorServerInterceptor interceptor) throws Exception { + RpcApiService rpcApiService = mock(RpcApiService.class); + given(rpcApiService.getDatabaseApi()).willReturn(RpcApiService.DatabaseApi.class + .getDeclaredConstructor(RpcApiService.class).newInstance(rpcApiService)); + given(rpcApiService.getWalletSolidityApi()).willReturn(RpcApiService.WalletSolidityApi.class + .getDeclaredConstructor(RpcApiService.class).newInstance(rpcApiService)); + + Object service = mock(serviceClass, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); + inject(serviceClass, service, rpcApiService); + inject(serviceClass, service, interceptor); + + NettyServerBuilder builder = mock(NettyServerBuilder.class); + Method addService = serviceClass.getDeclaredMethod("addService", NettyServerBuilder.class); + addService.setAccessible(true); + addService.invoke(service, builder); + + verify(builder, never()).addService(any(BindableService.class)); + ArgumentCaptor registered = + ArgumentCaptor.forClass(ServerServiceDefinition.class); + verify(builder, times(2)).addService(registered.capture()); + + Set names = new HashSet<>(); + for (ServerServiceDefinition definition : registered.getAllValues()) { + names.add(definition.getServiceDescriptor().getName()); + } + return names; + } + + /** Sets the one declared field the value fits; the two injected types are unrelated. */ + private static void inject(Class serviceClass, Object service, Object value) throws Exception { + for (Field field : serviceClass.getDeclaredFields()) { + if (field.getType().isInstance(value)) { + field.setAccessible(true); + field.set(service, value); + return; + } + } + Assert.fail(serviceClass.getSimpleName() + " has no field for " + value.getClass().getName()); + } +} diff --git a/framework/src/test/java/org/tron/core/services/filter/HttpInterceptorMetricsTest.java b/framework/src/test/java/org/tron/core/services/filter/HttpInterceptorMetricsTest.java new file mode 100644 index 00000000000..a9931dcdf8b --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/filter/HttpInterceptorMetricsTest.java @@ -0,0 +1,314 @@ +package org.tron.core.services.filter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import io.prometheus.client.CollectorRegistry; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.EnumSet; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import javax.servlet.DispatcherType; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.eclipse.jetty.servlet.FilterHolder; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.tron.common.TestConstants; +import org.tron.common.application.HttpService; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.prometheus.MetricKeys; +import org.tron.common.prometheus.MetricLabels; +import org.tron.common.utils.PublicMethod; +import org.tron.core.config.args.Args; +import org.tron.core.metrics.MetricsKey; +import org.tron.core.metrics.MetricsUtil; + +public class HttpInterceptorMetricsTest { + + private static final String BODY = "{\"blockID\":\"0123456789abcdef\"}"; + private static final int MULTI_BYTE_CODE_POINT = 0x6D4B; + private static final String UTF8_BODY = + "{\"name\":\"" + new String(Character.toChars(MULTI_BYTE_CODE_POINT)) + "\"}"; + private static final int BIG_BODY_SIZE = 200_000; + + private static final String HTTP_BYTES_SUM = MetricKeys.Histogram.HTTP_BYTES + "_sum"; + private static final String HTTP_BYTES_COUNT = MetricKeys.Histogram.HTTP_BYTES + "_count"; + private static final String[] HTTP_BYTES_LABELS = new String[] {"url", "status"}; + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private static MetricsHttpService service; + private static URI serverUri; + private static CloseableHttpClient client; + + public static class PrintlnServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setContentType("application/json; charset=utf-8"); + resp.getWriter().println(BODY); + } + } + + public static class PrintServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setContentType("application/json; charset=utf-8"); + resp.getWriter().print(BODY); + } + } + + public static class StreamServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + byte[] bytes = BODY.getBytes(StandardCharsets.UTF_8); + resp.setContentType("application/json-rpc"); + resp.setContentLength(bytes.length); + resp.getOutputStream().write(bytes); + resp.getOutputStream().flush(); + } + } + + public static class Utf8Servlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setContentType("application/json; charset=utf-8"); + resp.getWriter().println(UTF8_BODY); + } + } + + public static class BigBodyServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setContentType("application/json; charset=utf-8"); + resp.getWriter().print(bigBody()); + } + } + + public static class ErrorStatusServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.setContentType("application/json; charset=utf-8"); + resp.getWriter().println(BODY); + } + } + + public static class CompletionLatchFilter implements Filter { + + private static volatile CountDownLatch latch = new CountDownLatch(0); + + static void expectOneRequest() { + latch = new CountDownLatch(1); + } + + static boolean awaitRequestAccounted() throws InterruptedException { + return latch.await(10, TimeUnit.SECONDS); + } + + @Override + public void init(FilterConfig filterConfig) { + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + try { + chain.doFilter(request, response); + } finally { + latch.countDown(); + } + } + + @Override + public void destroy() { + } + } + + static class MetricsHttpService extends HttpService { + MetricsHttpService(int port) { + this.port = port; + this.contextPath = "/"; + } + + @Override + protected void addServlet(ServletContextHandler context) { + context.addServlet(new ServletHolder(new PrintlnServlet()), "/wallet/println"); + context.addServlet(new ServletHolder(new PrintServlet()), "/wallet/print"); + context.addServlet(new ServletHolder(new StreamServlet()), "/wallet/stream"); + context.addServlet(new ServletHolder(new Utf8Servlet()), "/wallet/utf8"); + context.addServlet(new ServletHolder(new BigBodyServlet()), "/wallet/big"); + context.addServlet(new ServletHolder(new ErrorStatusServlet()), "/wallet/error"); + } + + @Override + protected void addFilter(ServletContextHandler context) { + context.addFilter(new FilterHolder(new CompletionLatchFilter()), "/*", + EnumSet.of(DispatcherType.REQUEST)); + context.addFilter(new FilterHolder(new HttpApiAccessFilter()), "/*", + EnumSet.allOf(DispatcherType.class)); + ServletHandler handler = new ServletHandler(); + FilterHolder fh = handler.addFilterWithMapping(HttpInterceptor.class, "/*", + EnumSet.of(DispatcherType.REQUEST)); + context.addFilter(fh, "/*", EnumSet.of(DispatcherType.REQUEST)); + } + } + + @BeforeClass + public static void setup() throws Exception { + Args.setParam(new String[] {"-d", temporaryFolder.newFolder().toString()}, + TestConstants.TEST_CONF); + CommonParameter.getInstance().setNodeMetricsEnable(true); + CommonParameter.getInstance().setMetricsPrometheusEnable(true); + + int port = PublicMethod.chooseRandomPort(); + service = new MetricsHttpService(port); + service.start().get(10, TimeUnit.SECONDS); + serverUri = new URI(String.format("http://localhost:%d/", port)); + client = HttpClients.createDefault(); + } + + @AfterClass + public static void teardown() throws Exception { + try { + if (client != null) { + client.close(); + } + } finally { + try { + if (service != null) { + service.stop(); + } + } finally { + Args.clearParam(); + } + } + } + + @Test + public void testPrintlnBodyIsCountedExactly() throws Exception { + assertTrafficMatchesWire("/wallet/println", BODY + System.lineSeparator()); + } + + @Test + public void testPrintBodyIsCountedExactly() throws Exception { + assertTrafficMatchesWire("/wallet/print", BODY); + } + + @Test + public void testOutputStreamBodyIsCountedExactly() throws Exception { + assertTrafficMatchesWire("/wallet/stream", BODY); + } + + @Test + public void testUtf8BodyIsCountedInBytesNotCharacters() throws Exception { + assertTrue("the UTF-8 body must be longer in bytes than in characters", + UTF8_BODY.getBytes(StandardCharsets.UTF_8).length > UTF8_BODY.length()); + assertTrafficMatchesWire("/wallet/utf8", UTF8_BODY + System.lineSeparator()); + } + + @Test + public void testBodyLargerThanOutputBufferIsCountedExactly() throws Exception { + assertTrafficMatchesWire("/wallet/big", bigBody()); + } + + @Test + public void testErrorStatusReportsGlobalTrafficOnly() throws Exception { + String path = "/wallet/error"; + String detailKey = MetricsKey.NET_API_DETAIL_OUT_TRAFFIC + path; + long trafficBefore = meterCount(MetricsKey.NET_API_OUT_TRAFFIC); + long detailBefore = meterCount(detailKey); + long failBefore = meterCount(MetricsKey.NET_API_FAIL_QPS); + double histogramBefore = httpBytesSum(MetricLabels.UNDEFINED, "400"); + + CompletionLatchFilter.expectOneRequest(); + HttpResponse resp = client.execute(new HttpGet(serverUri.resolve(path))); + assertEquals(400, resp.getStatusLine().getStatusCode()); + byte[] wire = EntityUtils.toByteArray(resp.getEntity()); + assertEquals(BODY + System.lineSeparator(), new String(wire, StandardCharsets.UTF_8)); + assertTrue("the filter must finish accounting before the metrics are read", + CompletionLatchFilter.awaitRequestAccounted()); + + assertEquals("global out-traffic must equal the bytes on the wire", + trafficBefore + wire.length, meterCount(MetricsKey.NET_API_OUT_TRAFFIC)); + assertEquals("a 4xx must not reach the per-endpoint traffic meter", + detailBefore, meterCount(detailKey)); + assertEquals("a 4xx must be counted as a failed call", + failBefore + 1, meterCount(MetricsKey.NET_API_FAIL_QPS)); + assertEquals("the 4xx histogram is labelled undefined, not with the endpoint", + histogramBefore + wire.length, httpBytesSum(MetricLabels.UNDEFINED, "400"), 0.0); + } + + private void assertTrafficMatchesWire(String path, String expectedBody) throws Exception { + String detailKey = MetricsKey.NET_API_DETAIL_OUT_TRAFFIC + path; + long trafficBefore = meterCount(MetricsKey.NET_API_OUT_TRAFFIC); + long detailBefore = meterCount(detailKey); + double histogramBefore = httpBytesSum(path, "200"); + double observationsBefore = httpBytesCount(path, "200"); + + CompletionLatchFilter.expectOneRequest(); + HttpResponse resp = client.execute(new HttpGet(serverUri.resolve(path))); + assertEquals(200, resp.getStatusLine().getStatusCode()); + byte[] wire = EntityUtils.toByteArray(resp.getEntity()); + assertTrue("the filter must finish accounting before the metrics are read", + CompletionLatchFilter.awaitRequestAccounted()); + + assertEquals("the servlet body must reach the client intact", + expectedBody, new String(wire, StandardCharsets.UTF_8)); + assertEquals("global out-traffic must equal the bytes on the wire", + trafficBefore + wire.length, meterCount(MetricsKey.NET_API_OUT_TRAFFIC)); + assertEquals("per-endpoint out-traffic must equal the bytes on the wire", + detailBefore + wire.length, meterCount(detailKey)); + assertEquals("the histogram must be observed once, labelled with the endpoint", + observationsBefore + 1, httpBytesCount(path, "200"), 0.0); + assertEquals("the histogram must record the bytes on the wire", + histogramBefore + wire.length, httpBytesSum(path, "200"), 0.0); + } + + private long meterCount(String key) { + return MetricsUtil.getMeter(key).getCount(); + } + + private double httpBytesSum(String url, String status) { + return sampleValue(HTTP_BYTES_SUM, url, status); + } + + private double httpBytesCount(String url, String status) { + return sampleValue(HTTP_BYTES_COUNT, url, status); + } + + private double sampleValue(String name, String url, String status) { + Double value = CollectorRegistry.defaultRegistry.getSampleValue(name, HTTP_BYTES_LABELS, + new String[] {url, status}); + return value == null ? 0d : value; + } + + private static String bigBody() { + StringBuilder sb = new StringBuilder(BIG_BODY_SIZE); + while (sb.length() < BIG_BODY_SIZE) { + sb.append('a'); + } + return sb.toString(); + } +} diff --git a/framework/src/test/java/org/tron/core/services/filter/HttpInterceptorTest.java b/framework/src/test/java/org/tron/core/services/filter/HttpInterceptorTest.java index b293e8047b5..71f6cff6da3 100644 --- a/framework/src/test/java/org/tron/core/services/filter/HttpInterceptorTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/HttpInterceptorTest.java @@ -1,17 +1,27 @@ package org.tron.core.services.filter; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import javax.servlet.FilterChain; import javax.servlet.ServletException; import org.eclipse.jetty.http.BadMessageException; import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.Response; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.parameter.CommonParameter; +import org.tron.core.metrics.MetricsKey; +import org.tron.core.metrics.MetricsUtil; public class HttpInterceptorTest { + private static final String ENDPOINT = "/wallet/getnowblock"; + private final HttpInterceptor interceptor = new HttpInterceptor(); @Test @@ -27,7 +37,7 @@ public void testOversizedBadMessagePropagates() { BadMessageException e = assertThrows(BadMessageException.class, () -> interceptor.doFilter(request, response, chain)); - org.junit.Assert.assertEquals(HttpStatus.PAYLOAD_TOO_LARGE_413, e.getCode()); + assertEquals(HttpStatus.PAYLOAD_TOO_LARGE_413, e.getCode()); } @Test @@ -41,4 +51,61 @@ public void testNonOversizedExceptionIsStillSwallowed() throws Exception { interceptor.doFilter(request, response, chain); } + + @Test + public void testNonJettyRequestRecordsZeroSizeAndNoFailure() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest("GET", ENDPOINT); + request.setServletPath(ENDPOINT); + MockHttpServletResponse response = new MockHttpServletResponse(); + + boolean metricsWereEnabled = CommonParameter.getInstance().isNodeMetricsEnable(); + CommonParameter.getInstance().setNodeMetricsEnable(true); + try { + long trafficBefore = meterCount(MetricsKey.NET_API_OUT_TRAFFIC); + long qpsBefore = meterCount(MetricsKey.NET_API_QPS); + long failBefore = meterCount(MetricsKey.NET_API_FAIL_QPS); + + interceptor.doFilter(request, response, (req, resp) -> resp.getWriter().print("body")); + + assertEquals("body", response.getContentAsString()); + assertEquals(trafficBefore, meterCount(MetricsKey.NET_API_OUT_TRAFFIC)); + assertEquals(qpsBefore + 1, meterCount(MetricsKey.NET_API_QPS)); + assertEquals(failBefore, meterCount(MetricsKey.NET_API_FAIL_QPS)); + } finally { + CommonParameter.getInstance().setNodeMetricsEnable(metricsWereEnabled); + } + } + + @Test + public void testContentCountRecordedAsOutTraffic() throws Exception { + Response jettyResponse = mock(Response.class); + when(jettyResponse.getContentCount()).thenReturn(123L); + Request jettyRequest = mock(Request.class); + when(jettyRequest.getResponse()).thenReturn(jettyResponse); + when(jettyRequest.getContextPath()).thenReturn(""); + when(jettyRequest.getServletPath()).thenReturn(ENDPOINT); + MockHttpServletResponse response = new MockHttpServletResponse(); + + boolean metricsWereEnabled = CommonParameter.getInstance().isNodeMetricsEnable(); + CommonParameter.getInstance().setNodeMetricsEnable(true); + try { + long trafficBefore = meterCount(MetricsKey.NET_API_OUT_TRAFFIC); + long detailBefore = meterCount(MetricsKey.NET_API_DETAIL_OUT_TRAFFIC + ENDPOINT); + long failBefore = meterCount(MetricsKey.NET_API_FAIL_QPS); + + interceptor.doFilter(jettyRequest, response, (req, resp) -> { + }); + + assertEquals(trafficBefore + 123L, meterCount(MetricsKey.NET_API_OUT_TRAFFIC)); + assertEquals(detailBefore + 123L, + meterCount(MetricsKey.NET_API_DETAIL_OUT_TRAFFIC + ENDPOINT)); + assertEquals(failBefore, meterCount(MetricsKey.NET_API_FAIL_QPS)); + } finally { + CommonParameter.getInstance().setNodeMetricsEnable(metricsWereEnabled); + } + } + + private long meterCount(String key) { + return MetricsUtil.getMeter(key).getCount(); + } } diff --git a/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java b/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java index d6bf3850f30..532ddcd5521 100644 --- a/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java +++ b/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java @@ -156,7 +156,7 @@ public void doPostTest() throws IOException { while ((text = bufferedReader.readLine()) != null) { sb.append(text); } - Assert.assertTrue(sb.toString().contains("null")); + Assert.assertTrue(sb.toString().contains("{\"Error\":\"internal server error\"}")); httpUrlConnection.disconnect(); } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/services/http/JsonFormatEscapeTest.java b/framework/src/test/java/org/tron/core/services/http/JsonFormatEscapeTest.java index a5c74cc434d..9a5414b0154 100644 --- a/framework/src/test/java/org/tron/core/services/http/JsonFormatEscapeTest.java +++ b/framework/src/test/java/org/tron/core/services/http/JsonFormatEscapeTest.java @@ -12,6 +12,7 @@ import com.fasterxml.jackson.databind.json.JsonMapper; import com.google.protobuf.Any; import com.google.protobuf.ByteString; +import java.nio.CharBuffer; import java.nio.charset.StandardCharsets; import org.junit.Test; import org.tron.common.utils.ByteArray; @@ -224,6 +225,28 @@ public void testSupplementaryPlaneIsEmittedAsSurrogateEscapes() { assertEquals("\\ud83d\\ude00", escapeName(emoji, URL_FIELD)); } + @Test + public void testIsolatedLowSurrogatesKeepLegacyReplacement() throws Exception { + for (char low = Character.MIN_LOW_SURROGATE; low <= Character.MAX_LOW_SURROGATE; low++) { + String input = String.valueOf(low); + String escaped = JsonFormat.escapeText(input); + + assertEquals("?", escaped); + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(escaped)); + } + } + + @Test + public void testLowSurrogateReplacementPreservesFollowingCharacters() { + String low = String.valueOf((char) 0xDE00); + String emoji = new String(Character.toChars(0x1F600)); + + assertEquals("prefix?suffix", JsonFormat.escapeText("prefix" + low + "suffix")); + assertEquals("??", JsonFormat.escapeText(low + low)); + assertEquals("?\\n\\\"\\\\", JsonFormat.escapeText(low + "\n\"\\")); + assertEquals("?\\ud83d\\ude00", JsonFormat.escapeText(low + emoji)); + } + // Field integrity through HTTP normalization /** diff --git a/framework/src/test/java/org/tron/core/services/http/JsonFormatIdentifierTest.java b/framework/src/test/java/org/tron/core/services/http/JsonFormatIdentifierTest.java new file mode 100644 index 00000000000..f77d3730b9c --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/JsonFormatIdentifierTest.java @@ -0,0 +1,122 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.server.LocalConnector; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.junit.Test; +import org.tron.json.JSONObject; +import org.tron.protos.Protocol.Account; + +public class JsonFormatIdentifierTest { + + private static final String EMOJI = new String(Character.toChars(0x1F600)); + + @Test + public void testSupplementaryCharacterKeepsLegacyReplacement() { + assertIdentifierError(EMOJI, "?"); + assertIdentifierError("prefix" + EMOJI, "?"); + } + + @Test + public void testUnpairedSurrogatesKeepLegacyReplacement() { + String highSurrogate = String.valueOf((char) 0xD83D); + String lowSurrogate = String.valueOf((char) 0xDE00); + + assertIdentifierError(highSurrogate, "?"); + assertIdentifierError(highSurrogate + "a", "?"); + assertIdentifierError(highSurrogate + highSurrogate, "?"); + assertIdentifierError(lowSurrogate, "?"); + assertIdentifierError(lowSurrogate + highSurrogate, "?"); + } + + @Test + public void testOtherInvalidCharactersKeepTheirErrorMessages() { + String bmpCharacter = String.valueOf((char) 0x4E2D); + + assertIdentifierError("@", "@"); + assertIdentifierError("bad-name", "-"); + assertIdentifierError(bmpCharacter, bmpCharacter); + } + + @Test + public void testValidIdentifierStillParses() throws Exception { + Account.Builder account = Account.newBuilder(); + + JsonFormat.merge("{\"balance\":7}", account, false); + + assertEquals(7L, account.getBalance()); + } + + @Test + public void testIdentifierErrorIsValidUtf8WithNativeJettyWriter() throws Exception { + Server server = new Server(); + LocalConnector connector = new LocalConnector(server); + server.addConnector(connector); + ServletContextHandler context = new ServletContextHandler(); + context.setContextPath("/"); + context.addServlet(new ServletHolder(new IdentifierServlet()), "/parse"); + server.setHandler(context); + + try { + server.start(); + byte[] body = ("{\"" + EMOJI + "\":1}").getBytes(StandardCharsets.UTF_8); + byte[] headers = ("POST /parse HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "Connection: close\r\n" + + "Content-Type: application/json; charset=utf-8\r\n" + + "Content-Length: " + body.length + "\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII); + ByteBuffer request = ByteBuffer.allocate(headers.length + body.length); + request.put(headers).put(body).flip(); + + ByteBuffer response = connector.getResponse(request); + byte[] wire = new byte[response.remaining()]; + response.get(wire); + String raw = new String(wire, StandardCharsets.ISO_8859_1); + assertTrue(raw.startsWith("HTTP/1.1 200 ")); + int headerEnd = raw.indexOf("\r\n\r\n"); + assertTrue("the response must contain complete headers", headerEnd >= 0); + byte[] payload = Arrays.copyOfRange(wire, headerEnd + 4, wire.length); + + // String(byte[], UTF_8) replaces malformed bytes and would hide this regression. + String json = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(payload)).toString(); + String error = JSONObject.parseObject(json).getString("Error"); + assertEquals("1:2: Expected identifier. -?", error); + } finally { + server.stop(); + } + } + + private static void assertIdentifierError(String identifier, String expectedCharacter) { + JsonFormat.ParseException error = assertThrows(JsonFormat.ParseException.class, + () -> JsonFormat.merge("{\"" + identifier + "\":1}", Account.newBuilder(), false)); + + assertEquals("1:2: Expected identifier. -" + expectedCharacter, error.getMessage()); + } + + private static class IdentifierServlet extends HttpServlet { + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws IOException { + response.setContentType("application/json; charset=utf-8"); + try { + JsonFormat.merge(request.getReader(), Account.newBuilder(), false); + } catch (JsonFormat.ParseException e) { + Util.processError(e, response); + } + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/JsonFormatUnicodeErrorTest.java b/framework/src/test/java/org/tron/core/services/http/JsonFormatUnicodeErrorTest.java new file mode 100644 index 00000000000..e5d9d5146c8 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/JsonFormatUnicodeErrorTest.java @@ -0,0 +1,186 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import org.eclipse.jetty.server.LocalConnector; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.junit.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.tron.common.parameter.CommonParameter; +import org.tron.core.config.args.Args; +import org.tron.core.services.ratelimiter.RateLimiterContainer; +import org.tron.json.JSONObject; +import org.tron.protos.Protocol.Account; + +public class JsonFormatUnicodeErrorTest { + + private static final String EMOJI = new String(Character.toChars(0x1F600)); + + @Test + public void testInvalidSupplementaryEscapeKeepsLegacyReplacement() { + assertEscapeError("\\" + EMOJI, "?"); + assertEscapeError("prefix\\" + EMOJI, "?"); + } + + @Test + public void testInvalidUnpairedSurrogateEscapesKeepLegacyReplacement() { + String highSurrogate = String.valueOf((char) 0xD83D); + String lowSurrogate = String.valueOf((char) 0xDE00); + + assertEscapeError("\\" + highSurrogate, "?"); + assertEscapeError("\\" + highSurrogate + "a", "?"); + assertEscapeError("\\" + highSurrogate + highSurrogate, "?"); + assertEscapeError("\\" + lowSurrogate, "?"); + assertEscapeError("\\" + lowSurrogate + highSurrogate, "?"); + } + + @Test + public void testOtherInvalidEscapesKeepTheirErrorMessages() { + String bmpCharacter = String.valueOf((char) 0x4E2D); + + assertEscapeError("\\q", "q"); + assertEscapeError("\\@", "@"); + assertEscapeError("\\" + bmpCharacter, bmpCharacter); + } + + @Test + public void testValidUnicodeAndEscapesStillDecode() throws Exception { + String bmpCharacter = String.valueOf((char) 0x4E2D); + + assertEquals(bmpCharacter + EMOJI, JsonFormat.unescapeText(bmpCharacter + EMOJI)); + assertEquals("\b\f\n\r\t\\/\"'" + bmpCharacter + EMOJI, + JsonFormat.unescapeText("\\b\\f\\n\\r\\t\\\\\\/\\\"\\'\\u4e2d\\uD83D\\uDE00")); + } + + @Test + public void testDeployContractEscapeErrorIsValidUtf8WithNativeJettyWriter() throws Exception { + JSONObject input = new JSONObject(); + input.put("owner_address", ""); + // The outer JSON is valid; only the embedded ABI contains an invalid escape. + input.put("abi", "[{\"name\":\"\\" + EMOJI + "\"}]"); + + String error = requestError(new DeployContractServlet(), "/wallet/deploycontract", input); + + assertEquals("1:20: Invalid escape sequence: '\\?'", error); + } + + @Test + public void testLongIntegerErrorIsValidUtf8WithNativeJettyWriter() throws Exception { + JSONObject input = new JSONObject(); + // BigInteger's digit groups can split a surrogate pair inside its exception message. + input.put("balance", "11111" + EMOJI + "1111111"); + + String error = requestError(new GetAccountServlet(), "/wallet/getaccount", input); + + assertTrue(error.contains("1:12: Couldn't parse integer:")); + } + + @Test + public void testParserErrorsReplaceOnlyUnpairedSurrogates() throws Exception { + String high = String.valueOf((char) 0xD800); + String low = String.valueOf((char) 0xDC00); + String description = high + "x" + EMOJI + low + high; + String expected = "?x" + EMOJI + "??"; + JsonFormat.Tokenizer tokenizer = new JsonFormat.Tokenizer("first second"); + tokenizer.nextToken(); + + String current = tokenizer.parseException(description).getMessage(); + String previous = tokenizer.parseExceptionPreviousToken(description).getMessage(); + + assertEquals("1:7: " + expected, current); + assertEquals("1:1: " + expected, previous); + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(current)); + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(previous)); + } + + @Test + public void testParserErrorsPreserveValidDescriptions() { + String description = "invalid " + (char) 0x4E2D + EMOJI; + JsonFormat.Tokenizer tokenizer = new JsonFormat.Tokenizer("field"); + + assertEquals("1:1: " + description, tokenizer.parseException(description).getMessage()); + assertEquals("1:1: " + description, + tokenizer.parseExceptionPreviousToken(description).getMessage()); + assertEquals("1:1: null", tokenizer.parseException(null).getMessage()); + assertEquals("1:1: null", tokenizer.parseExceptionPreviousToken(null).getMessage()); + } + + @Test + public void testOrdinaryIntegerErrorsKeepTheirMessages() { + JsonFormat.ParseException invalid = assertThrows(JsonFormat.ParseException.class, + () -> JsonFormat.merge("{\"balance\":\"bad\"}", Account.newBuilder(), false)); + JsonFormat.ParseException overflow = assertThrows(JsonFormat.ParseException.class, + () -> JsonFormat.merge("{\"balance\":9223372036854775808}", + Account.newBuilder(), false)); + + assertEquals("1:12: Couldn't parse integer: For input string: \"\"bad\"\"", + invalid.getMessage()); + assertEquals("1:12: Couldn't parse integer: Number out of range for 64-bit signed integer: " + + "9223372036854775808", overflow.getMessage()); + } + + private static String requestError(RateLimiterServlet servlet, String path, JSONObject input) + throws Exception { + CommonParameter args = Args.getInstance(); + long originalMaxSize = args.getHttpMaxMessageSize(); + boolean originalNonBlocking = args.isRateLimiterApiNonBlocking(); + Server server = new Server(); + LocalConnector connector = new LocalConnector(server); + server.addConnector(connector); + ServletContextHandler context = new ServletContextHandler(); + context.setContextPath("/"); + ReflectionTestUtils.setField(servlet, "container", new RateLimiterContainer()); + context.addServlet(new ServletHolder(servlet), path); + server.setHandler(context); + + try { + args.setHttpMaxMessageSize(1_000_000L); + args.setRateLimiterApiNonBlocking(false); + server.start(); + byte[] body = input.toJSONString().getBytes(StandardCharsets.UTF_8); + byte[] headers = ("POST " + path + " HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "Connection: close\r\n" + + "Content-Type: application/json; charset=utf-8\r\n" + + "Content-Length: " + body.length + "\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII); + ByteBuffer request = ByteBuffer.allocate(headers.length + body.length); + request.put(headers).put(body).flip(); + + ByteBuffer response = connector.getResponse(request); + byte[] wire = new byte[response.remaining()]; + response.get(wire); + String raw = new String(wire, StandardCharsets.ISO_8859_1); + assertTrue(raw.startsWith("HTTP/1.1 200 ")); + int headerEnd = raw.indexOf("\r\n\r\n"); + assertTrue("the response must contain complete headers", headerEnd >= 0); + byte[] payload = Arrays.copyOfRange(wire, headerEnd + 4, wire.length); + + // A replacement decoder would hide invalid bytes emitted by the response writer. + String json = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(payload)).toString(); + return JSONObject.parseObject(json).getString("Error"); + } finally { + try { + server.stop(); + } finally { + args.setHttpMaxMessageSize(originalMaxSize); + args.setRateLimiterApiNonBlocking(originalNonBlocking); + } + } + } + + private static void assertEscapeError(String input, String expectedCharacter) { + JsonFormat.InvalidEscapeSequence error = assertThrows(JsonFormat.InvalidEscapeSequence.class, + () -> JsonFormat.unescapeText(input)); + + assertEquals("Invalid escape sequence: '\\" + expectedCharacter + "'", error.getMessage()); + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/JsonRpcRateLimiterServletTest.java b/framework/src/test/java/org/tron/core/services/http/JsonRpcRateLimiterServletTest.java new file mode 100644 index 00000000000..52ff23a7d2d --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/JsonRpcRateLimiterServletTest.java @@ -0,0 +1,129 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.googlecode.jsonrpc4j.JsonRpcServer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.mockito.MockedStatic; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.util.ReflectionTestUtils; +import org.tron.common.TestConstants; +import org.tron.core.config.args.Args; +import org.tron.core.services.interfaceJsonRpcOnPBFT.JsonRpcOnPBFTServlet; +import org.tron.core.services.interfaceJsonRpcOnSolidity.JsonRpcOnSolidityServlet; +import org.tron.core.services.interfaceOnPBFT.WalletOnPBFT; +import org.tron.core.services.interfaceOnSolidity.WalletOnSolidity; +import org.tron.core.services.jsonrpc.JsonRpcServlet; +import org.tron.core.services.ratelimiter.GlobalRateLimiter; +import org.tron.core.services.ratelimiter.RateLimiterContainer; +import org.tron.core.services.ratelimiter.RuntimeData; +import org.tron.core.services.ratelimiter.adapter.IRateLimiter; + +@RunWith(Parameterized.class) +public class JsonRpcRateLimiterServletTest { + + private final Class servletClass; + private RateLimiterServlet servlet; + private IRateLimiter perEndpoint; + private Object dispatcher; + private MockHttpServletRequest request; + private MockHttpServletResponse response; + + public JsonRpcRateLimiterServletTest(Class servletClass) { + this.servletClass = servletClass; + } + + @Parameterized.Parameters(name = "{0}") + public static Collection servlets() { + return Arrays.asList(new Object[][] { + {JsonRpcServlet.class}, + {JsonRpcOnSolidityServlet.class}, + {JsonRpcOnPBFTServlet.class} + }); + } + + @Before + public void setUp() throws Exception { + // Initialize Args before GlobalRateLimiter's static QPS limiters are loaded. + Args.setParam(new String[0], TestConstants.TEST_CONF); + servlet = servletClass.getDeclaredConstructor().newInstance(); + RateLimiterContainer container = new RateLimiterContainer(); + perEndpoint = mock(IRateLimiter.class); + container.add("http_", servletClass.getSimpleName(), perEndpoint); + ReflectionTestUtils.setField(servlet, "container", container); + + if (servlet instanceof JsonRpcOnSolidityServlet) { + dispatcher = mock(WalletOnSolidity.class); + ReflectionTestUtils.setField(servlet, "walletOnSolidity", dispatcher); + } else if (servlet instanceof JsonRpcOnPBFTServlet) { + dispatcher = mock(WalletOnPBFT.class); + ReflectionTestUtils.setField(servlet, "walletOnPBFT", dispatcher); + } else { + dispatcher = mock(JsonRpcServer.class); + ReflectionTestUtils.setField(servlet, "rpcServer", dispatcher); + } + + request = new MockHttpServletRequest("POST", "/jsonrpc"); + request.setServletPath("/jsonrpc"); + request.setRemoteAddr("10.0.0.1"); + request.setContentType("application/json"); + request.setContent("{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"id\":1}" + .getBytes(StandardCharsets.UTF_8)); + response = new MockHttpServletResponse(); + } + + @After + public void tearDown() { + Args.clearParam(); + } + + @Test + public void testPerEndpointRejectionReturnsSanitizedHttpError() throws Exception { + when(perEndpoint.acquirePermit(any(RuntimeData.class))).thenReturn(false); + + try (MockedStatic global = mockStatic(GlobalRateLimiter.class)) { + servlet.service(request, response); + + global.verify(() -> GlobalRateLimiter.acquirePermit(any()), never()); + assertRateLimitResponse(); + } + } + + @Test + public void testGlobalRejectionReturnsSanitizedHttpError() throws Exception { + when(perEndpoint.acquirePermit(any(RuntimeData.class))).thenReturn(true); + + try (MockedStatic global = mockStatic(GlobalRateLimiter.class)) { + global.when(() -> GlobalRateLimiter.acquirePermit(any())).thenReturn(false); + + servlet.service(request, response); + + global.verify(() -> GlobalRateLimiter.acquirePermit(any())); + assertRateLimitResponse(); + } + } + + private void assertRateLimitResponse() throws Exception { + assertEquals(200, response.getStatus()); + assertEquals("application/json; charset=utf-8", response.getContentType()); + assertEquals("{\"Error\":\"lack of computing resources\"}", + response.getContentAsString().trim()); + verify(perEndpoint).acquirePermit(any(RuntimeData.class)); + verifyNoInteractions(dispatcher); + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/OutboundJsonTest.java b/framework/src/test/java/org/tron/core/services/http/OutboundJsonTest.java new file mode 100644 index 00000000000..f76765c0817 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/OutboundJsonTest.java @@ -0,0 +1,191 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.util.ReflectionTestUtils; +import org.tron.api.GrpcAPI.BytesMessage; +import org.tron.api.GrpcAPI.TransactionIdList; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.StringUtil; +import org.tron.core.Wallet; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.config.args.Args; +import org.tron.json.JSONArray; +import org.tron.json.JSONObject; +import org.tron.protos.Protocol.Transaction; +import org.tron.protos.Protocol.Transaction.Contract; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; +import org.tron.protos.contract.SmartContractOuterClass.SmartContract; +import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; + +public class OutboundJsonTest { + + private static final String OWNER_ADDRESS = "41c076305e35aea1fe45a772fcaaab8a36e87bdb55"; + private static final ByteString OWNER = + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)); + private static final long TIMESTAMP = 1_700_000_000_000L; + + private long savedHttpMaxMessageSize; + + @Before + public void setUp() { + JsonFormat.clearInt64AsString(); + savedHttpMaxMessageSize = Args.getInstance().getHttpMaxMessageSize(); + Args.getInstance().setHttpMaxMessageSize(1_024); + } + + @After + public void tearDown() { + JsonFormat.clearInt64AsString(); + Args.getInstance().setHttpMaxMessageSize(savedHttpMaxMessageSize); + } + + @Test + public void testPrintTransactionWithAbi() { + int entryCount = 2; + SmartContract.ABI.Builder abi = SmartContract.ABI.newBuilder(); + for (int i = 0; i < entryCount; i++) { + abi.addEntrys(SmartContract.ABI.Entry.newBuilder().setName("f" + i) + .setType(SmartContract.ABI.Entry.EntryType.Function)); + } + ByteString bytecode = ByteString.copyFrom(new byte[] {0}); + CreateSmartContract create = CreateSmartContract.newBuilder().setOwnerAddress(OWNER) + .setNewContract(SmartContract.newBuilder().setOriginAddress(OWNER).setAbi(abi) + .setBytecode(bytecode)) + .build(); + Transaction transaction = transaction(ContractType.CreateSmartContract, Any.pack(create)); + JSONObject output = Util.printTransactionToJSON(transaction, false); + JSONObject contract = output.getJSONObject("raw_data").getJSONArray("contract") + .getJSONObject(0); + JSONObject value = contract.getJSONObject("parameter").getJSONObject("value"); + JSONArray entries = value.getJSONObject("new_contract").getJSONObject("abi") + .getJSONArray("entrys"); + assertEquals(entryCount, entries.size()); + assertEquals("f0", entries.getJSONObject(0).getString("name")); + assertEquals("f1", entries.getJSONObject(entryCount - 1).getString("name")); + assertEquals("Function", entries.getJSONObject(0).getString("type")); + assertEquals("CreateSmartContract", contract.getString("type")); + assertEquals(OWNER_ADDRESS, value.getString("owner_address")); + byte[] contractAddress = Util.generateContractAddress(transaction, OWNER.toByteArray()); + assertEquals(ByteArray.toHexString(contractAddress), + output.getString("contract_address")); + assertTransactionIdentity(transaction, output); + + JSONObject serialized = JSONObject.outboundParseObject(output.toJSONString()); + assertEquals(output, serialized); + } + + @Test + public void testPrintTransactionIdList() { + int count = 3; + TransactionIdList.Builder builder = TransactionIdList.newBuilder(); + for (int i = 0; i < count; i++) { + builder.addTxId("tx" + i); + } + TransactionIdList list = builder.build(); + JSONObject output = JSONObject.outboundParseObject(Util.printTransactionIdList(list, false)); + JSONArray ids = output.getJSONArray("txId"); + assertEquals(count, ids.size()); + assertEquals("tx0", ids.getString(0)); + assertEquals("tx" + (count - 1), ids.getString(count - 1)); + } + + @Test + public void testPrintTransactionPreservesVisibleAndInt64Formatting() { + long callValue = 9_007_199_254_740_993L; + TriggerSmartContract trigger = TriggerSmartContract.newBuilder().setOwnerAddress(OWNER) + .setContractAddress(OWNER).setCallValue(callValue).build(); + Transaction transaction = transaction(ContractType.TriggerSmartContract, Any.pack(trigger)); + for (boolean visible : new boolean[] {false, true}) { + for (boolean int64AsString : new boolean[] {false, true}) { + JsonFormat.setInt64AsString(int64AsString); + JSONObject output = Util.printTransactionToJSON(transaction, visible); + JSONObject rawData = output.getJSONObject("raw_data"); + JSONObject contract = rawData.getJSONArray("contract").getJSONObject(0); + JSONObject value = contract.getJSONObject("parameter").getJSONObject("value"); + String address = visible ? StringUtil.encode58Check(OWNER.toByteArray()) : OWNER_ADDRESS; + assertEquals(address, value.getString("owner_address")); + assertEquals(address, value.getString("contract_address")); + assertEquals("TriggerSmartContract", contract.getString("type")); + assertEquals(int64AsString, value.unwrap().get("call_value").isTextual()); + assertEquals(int64AsString, rawData.unwrap().get("timestamp").isTextual()); + assertEquals(callValue, value.getLongValue("call_value")); + assertEquals(TIMESTAMP, rawData.getLongValue("timestamp")); + assertTransactionIdentity(transaction, output); + } + } + } + + @Test + public void testPrintTransactionFeePreservesReceipt() { + String input = "{\"receipt\":{\"energy_fee\":100,\"net_fee\":20}}"; + JSONObject output = JSONObject.parseObject(Util.printTransactionFee(input)); + assertEquals(JSONObject.parseObject(input).getJSONObject("receipt"), + output.getJSONObject("Receipt")); + assertEquals(100, output.getJSONObject("Receipt").getLongValue("energy_fee")); + assertEquals(20, output.getJSONObject("Receipt").getLongValue("net_fee")); + } + + @Test + public void testGetContractPreservesAddressesForGetAndPost() throws Exception { + SmartContract contract = SmartContract.newBuilder().setName("normal-contract") + .setOriginAddress(OWNER).setContractAddress(OWNER).build(); + Wallet wallet = mock(Wallet.class); + when(wallet.getContract(BytesMessage.newBuilder().setValue(OWNER).build())) + .thenReturn(contract); + GetContractServlet servlet = new GetContractServlet(); + ReflectionTestUtils.setField(servlet, "wallet", wallet); + for (boolean visible : new boolean[] {false, true}) { + String address = visible ? StringUtil.encode58Check(OWNER.toByteArray()) : OWNER_ADDRESS; + MockHttpServletRequest get = new MockHttpServletRequest("GET", "/wallet/getcontract"); + get.setParameter("value", address); + get.setParameter("visible", Boolean.toString(visible)); + MockHttpServletResponse getResponse = new MockHttpServletResponse(); + servlet.doGet(get, getResponse); + assertContractResponse(getResponse, address); + + JSONObject body = new JSONObject(); + body.put("value", address); + body.put("visible", visible); + MockHttpServletRequest post = new MockHttpServletRequest("POST", "/wallet/getcontract"); + post.setContentType("application/json"); + post.setContent(body.toJSONString().getBytes(StandardCharsets.UTF_8)); + MockHttpServletResponse postResponse = new MockHttpServletResponse(); + servlet.doPost(post, postResponse); + assertContractResponse(postResponse, address); + } + } + + private static void assertContractResponse(MockHttpServletResponse response, String address) + throws Exception { + assertEquals(200, response.getStatus()); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(response.getContentAsString(), "normal-contract", body.getString("name")); + assertEquals(address, body.getString("origin_address")); + assertEquals(address, body.getString("contract_address")); + } + + private static Transaction transaction(ContractType type, Any parameter) { + Contract contract = Contract.newBuilder().setType(type).setParameter(parameter).build(); + return Transaction.newBuilder().setRawData(Transaction.raw.newBuilder() + .setTimestamp(TIMESTAMP).addContract(contract)).build(); + } + + private static void assertTransactionIdentity(Transaction transaction, JSONObject output) { + assertEquals(ByteArray.toHexString(transaction.getRawData().toByteArray()), + output.getString("raw_data_hex")); + assertEquals(ByteArray.toHexString(new TransactionCapsule(transaction) + .getTransactionId().getBytes()), output.getString("txID")); + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/UtilMockTest.java b/framework/src/test/java/org/tron/core/services/http/UtilMockTest.java index d4124c90adf..ed43e960520 100644 --- a/framework/src/test/java/org/tron/core/services/http/UtilMockTest.java +++ b/framework/src/test/java/org/tron/core/services/http/UtilMockTest.java @@ -198,16 +198,6 @@ public void testPrintBlockToJSONCoversAllProtoTopLevelFields() { } } - @Test - public void testPrintTransactionList() { - TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); - GrpcAPI.TransactionList list = GrpcAPI.TransactionList.newBuilder() - .addTransaction(transactionCapsule.getInstance()) - .build(); - String out = Util.printTransactionList(list, true); - Assert.assertNotNull(out); - } - private TransactionCapsule getTransactionCapsuleExample() { final String OWNER_ADDRESS = "41548794500882809695a8a687866e76d4271a1abc"; final String RECEIVER_ADDRESS = "41abd4b9367799eaa3197fecb144eb71de1e049150"; diff --git a/framework/src/test/java/org/tron/core/services/http/UtilProcessErrorTest.java b/framework/src/test/java/org/tron/core/services/http/UtilProcessErrorTest.java new file mode 100644 index 00000000000..5d4baa34c6f --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/UtilProcessErrorTest.java @@ -0,0 +1,107 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +import com.google.protobuf.InvalidProtocolBufferException; +import org.bouncycastle.util.encoders.DecoderException; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.HeaderNotFound; +import org.tron.core.exception.MaintenanceUnavailableException; +import org.tron.core.exception.ZkProofValidateException; +import org.tron.json.JSONException; +import org.tron.json.JSONObject; + +public class UtilProcessErrorTest { + + private static final String INTERNAL_SERVER_ERROR = "internal server error"; + private static final String RATE_LIMITER_ERROR_MSG = "lack of computing resources"; + + @Test + public void exactCompatibilityTypesPreserveNonBlankMessage() throws Exception { + assertError(new JsonFormat.ParseException("1:2: invalid \"field\"\nvalue"), + "1:2: invalid \"field\"\nvalue"); + assertError(new ContractValidateException("balance is not sufficient"), + "balance is not sufficient"); + assertError(new MaintenanceUnavailableException("maintenance in progress"), + "maintenance in progress"); + } + + @Test + public void unclassifiedTypesFailClosed() throws Exception { + DecoderException decoder = assertThrows(DecoderException.class, () -> Hex.decode("zz")); + Exception[] errors = { + new NullPointerException("internal field name"), + new JSONException("server serialization detail"), + new InvalidProtocolBufferException("stored protobuf detail"), + decoder, + new HeaderNotFound("latest block not found"), + new IllegalArgumentException("No enum constant internal.Type.VALUE"), + new IllegalAccessException(RATE_LIMITER_ERROR_MSG), + new IllegalAccessException("other access failure"), + new ZkProofValidateException("wrapped validation detail", true) + }; + + for (Exception error : errors) { + assertError(error, INTERNAL_SERVER_ERROR); + } + } + + @Test + public void onlyExactFixedControlSignalsArePreserved() throws Exception { + assertError(new IllegalArgumentException(Util.EVENTS_DEPRECATED_MSG), + Util.EVENTS_DEPRECATED_MSG); + assertError(new IllegalArgumentException("other argument failure"), INTERNAL_SERVER_ERROR); + assertError(new NumberFormatException(Util.EVENTS_DEPRECATED_MSG), INTERNAL_SERVER_ERROR); + } + + @Test + public void nullBlankAndSubclassMessagesFailClosed() throws Exception { + assertError(null, INTERNAL_SERVER_ERROR); + assertError(new JsonFormat.ParseException(null), INTERNAL_SERVER_ERROR); + assertError(new JsonFormat.ParseException(""), INTERNAL_SERVER_ERROR); + assertError(new JsonFormat.ParseException(" "), INTERNAL_SERVER_ERROR); + assertError(new ContractValidateException("subclass message") { }, INTERNAL_SERVER_ERROR); + } + + @Test + public void auditedErrorWriterPreservesTextVerbatim() throws Exception { + for (String audited : new String[] {Util.INVALID_ADDRESS_MSG, Util.RATE_LIMITER_ERROR_MSG}) { + MockHttpServletResponse response = new MockHttpServletResponse(); + Util.writeAuditedError(audited, response); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(audited, body.getString("Error")); + } + } + + @Test + public void auditedErrorWriterWithNullMessageWritesEmptyObject() throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + Util.writeAuditedError(null, response); + assertEquals("{}", response.getContentAsString().trim()); + } + + @Test + public void serverErrorChannelSanitizesLikeTheSharedPath() throws Exception { + assertServerError(new NullPointerException("internal field name"), INTERNAL_SERVER_ERROR); + assertServerError(new ContractValidateException("balance is not sufficient"), + "balance is not sufficient"); + } + + private static void assertServerError(Exception error, String expected) throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + Util.processServerError(error, response); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(expected, body.getString("Error")); + } + + private static void assertError(Exception error, String expected) throws Exception { + MockHttpServletResponse response = new MockHttpServletResponse(); + Util.processError(error, response); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(expected, body.getString("Error")); + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java index e1abb41d1e1..cacb904d9b9 100644 --- a/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java +++ b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java @@ -1,202 +1,146 @@ package org.tron.core.services.http.solidity; -import static org.mockito.BDDMockito.given; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLStreamHandlerFactory; -import java.nio.charset.StandardCharsets; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import lombok.extern.slf4j.Slf4j; +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.Collection; import org.junit.After; -import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.utils.FileUtil; -import org.tron.common.utils.PublicMethod; -import org.tron.core.services.http.solidity.mockito.HttpUrlStreamHandler; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.util.ReflectionTestUtils; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.Wallet; +import org.tron.core.config.args.Args; +import org.tron.json.JSONObject; +import org.tron.protos.Protocol.Transaction; + +@RunWith(Parameterized.class) +public class GetTransactionByIdSolidityServletTest { + private static final String TRANSACTION_ID = + "309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef213f2c55225a8bd2"; + private static final ByteString TRANSACTION_ID_BYTES = + ByteString.copyFrom(ByteArray.fromHexString(TRANSACTION_ID)); -@Slf4j -public class GetTransactionByIdSolidityServletTest { + @Parameter + public String method; - private static HttpUrlStreamHandler httpUrlStreamHandler; - private GetTransactionByIdSolidityServlet getTransactionByIdSolidityServlet; - private HttpServletRequest request; - private HttpServletResponse response; - private HttpURLConnection httpUrlConnection; - private OutputStreamWriter outputStreamWriter; - private URL url; - - /** - * . - */ - @BeforeClass - public static void init() { - // Allows for mocking URL connections - URLStreamHandlerFactory urlStreamHandlerFactory = mock(URLStreamHandlerFactory.class); - try { - URL.setURLStreamHandlerFactory(urlStreamHandlerFactory); - } catch (Error e) { - logger.info("Ignore error: {}", e.getMessage()); - } + private GetTransactionByIdSolidityServlet servlet; + private Wallet wallet; + private long savedMaxMessageSize; - httpUrlStreamHandler = new HttpUrlStreamHandler(); - given(urlStreamHandlerFactory.createURLStreamHandler("http")).willReturn(httpUrlStreamHandler); + @Parameters(name = "{0}") + public static Collection methods() { + return Arrays.asList(new Object[][] {{"GET"}, {"POST"}}); } - /** - * Init. - */ - @Before public void setUp() { - getTransactionByIdSolidityServlet = new GetTransactionByIdSolidityServlet(); - this.request = mock(HttpServletRequest.class); - this.response = mock(HttpServletResponse.class); - this.httpUrlConnection = mock(HttpURLConnection.class); - this.outputStreamWriter = mock(OutputStreamWriter.class); - httpUrlStreamHandler.resetConnections(); + savedMaxMessageSize = Args.getInstance().getHttpMaxMessageSize(); + Args.getInstance().setHttpMaxMessageSize(1024); + servlet = new GetTransactionByIdSolidityServlet(); + wallet = mock(Wallet.class); + ReflectionTestUtils.setField(servlet, "wallet", wallet); } - /** - * Release Resource. - */ @After public void tearDown() { - if (FileUtil.deleteDir(new File("temp.txt"))) { - logger.info("Release resources successful."); + Args.getInstance().setHttpMaxMessageSize(savedMaxMessageSize); + } + + @Test + public void walletFailureReturnsSanitizedJson() throws Exception { + when(wallet.getTransactionById(TRANSACTION_ID_BYTES)) + .thenThrow(new NullPointerException("internal transaction store detail")); + + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals("internal server error", errorMessage(response)); + verify(wallet).getTransactionById(TRANSACTION_ID_BYTES); + } + + @Test + public void invalidHexReturnsJsonWithoutCallingWallet() throws Exception { + MockHttpServletResponse response = request("zz"); + + String message = errorMessage(response); + if ("GET".equals(method)) { + assertEquals("internal server error", message); } else { - logger.info("Release resources failure."); + assertTrue(message.matches("\\d+:\\d+: INVALID hex String")); } + verifyNoInteractions(wallet); } @Test - public void doPostTest() throws IOException { - - //send Post request - - final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - String href = "http://127.0.0.1:" - + PublicMethod.chooseRandomPort() + "/walletsolidity/gettransactioninfobyid"; - httpUrlStreamHandler.addConnection(new URL(href), httpUrlConnection); - httpUrlConnection.setRequestMethod("POST"); - httpUrlConnection.setRequestProperty("Content-Type", "application/json"); - httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); - httpUrlConnection.setUseCaches(false); - httpUrlConnection.setDoOutput(true); - String postData = "{\"value\": \"309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef21" - + "3f2c55225a8bd2\"}"; - httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(postData.length())); - - when(httpUrlConnection.getOutputStream()).thenReturn(outContent); - OutputStreamWriter out = new OutputStreamWriter(httpUrlConnection.getOutputStream(), - StandardCharsets.UTF_8); - out.write(postData); - out.flush(); - out.close(); - PrintWriter writer = new PrintWriter("temp.txt"); - when(response.getWriter()).thenReturn(writer); - - getTransactionByIdSolidityServlet.doPost(request, response); - // Get Response Body - String line; - StringBuilder result = new StringBuilder(); - - byte[] buffer = new byte[1024]; - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer); - when(httpUrlConnection.getInputStream()).thenReturn(byteArrayInputStream); - BufferedReader in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), - StandardCharsets.UTF_8)); - - while ((line = in.readLine()) != null) { - result.append(line).append("\n"); - } - Assert.assertNotNull(result); - in.close(); - writer.flush(); - FileInputStream fileInputStream = new FileInputStream("temp.txt"); - InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - - StringBuilder sb = new StringBuilder(); - String text; - while ((text = bufferedReader.readLine()) != null) { - sb.append(text); - } - Assert.assertTrue(sb.toString().contains("null")); - httpUrlConnection.disconnect(); + public void missingTransactionKeepsEmptyObject() throws Exception { + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals(200, response.getStatus()); + assertEquals("{}", response.getContentAsString().trim()); + verify(wallet).getTransactionById(TRANSACTION_ID_BYTES); } @Test - public void doGetTest() throws IOException { - - final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - String href = "http://127.0.0.1:" - + PublicMethod.chooseRandomPort() + "/walletsolidity/gettransactioninfobyid"; - httpUrlStreamHandler.addConnection(new URL(href), httpUrlConnection); - httpUrlConnection.setRequestMethod("GET"); - httpUrlConnection.setRequestProperty("Content-Type", "application/json"); - httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); - httpUrlConnection.setUseCaches(false); - httpUrlConnection.setDoOutput(true); - String postData = "{\"value\": \"309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef21" - + "3f2c55225a8bd2\"}"; - httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(postData.length())); - - when(httpUrlConnection.getOutputStream()).thenReturn(outContent); - OutputStreamWriter out = new OutputStreamWriter(httpUrlConnection.getOutputStream(), - StandardCharsets.UTF_8); - out.write(postData); - out.flush(); - out.close(); - PrintWriter writer = new PrintWriter("temp.txt"); - when(response.getWriter()).thenReturn(writer); - - getTransactionByIdSolidityServlet.doPost(request, response); - // Get Response Body - String line; - StringBuilder result = new StringBuilder(); - - byte[] buffer = new byte[1024]; - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer); - when(httpUrlConnection.getInputStream()).thenReturn(byteArrayInputStream); - BufferedReader in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), - StandardCharsets.UTF_8)); - - while ((line = in.readLine()) != null) { - result.append(line).append("\n"); - } - Assert.assertNotNull(result); - in.close(); - writer.flush(); - FileInputStream fileInputStream = new FileInputStream("temp.txt"); - InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); - BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - - StringBuilder sb = new StringBuilder(); - String text; - while ((text = bufferedReader.readLine()) != null) { - sb.append(text); + public void successfulLookupKeepsTransaction() throws Exception { + ByteString signature = ByteString.copyFromUtf8("transaction signature"); + Transaction transaction = Transaction.newBuilder() + .setRawData(Transaction.raw.newBuilder().setTimestamp(123).setExpiration(456)) + .addSignature(signature).build(); + when(wallet.getTransactionById(TRANSACTION_ID_BYTES)).thenReturn(transaction); + + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals(200, response.getStatus()); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(4, body.size()); + JSONObject rawData = body.getJSONObject("raw_data"); + assertEquals(123L, rawData.getLongValue("timestamp")); + assertEquals(456L, rawData.getLongValue("expiration")); + assertEquals(0, rawData.getJSONArray("contract").size()); + assertEquals(ByteArray.toHexString(transaction.getRawData().toByteArray()), + body.getString("raw_data_hex")); + assertEquals(Sha256Hash.of(Args.getInstance().isECKeyCryptoEngine(), + transaction.getRawData().toByteArray()).toString(), body.getString("txID")); + assertEquals(1, body.getJSONArray("signature").size()); + assertEquals(ByteArray.toHexString(signature.toByteArray()), + body.getJSONArray("signature").getString(0)); + verify(wallet).getTransactionById(TRANSACTION_ID_BYTES); + } + + private MockHttpServletResponse request(String value) throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(method, + "/walletsolidity/gettransactionbyid"); + MockHttpServletResponse response = new MockHttpServletResponse(); + if ("GET".equals(method)) { + request.setParameter("value", value); + servlet.doGet(request, response); + } else { + request.setContentType("application/json"); + request.setContent(("{\"value\":\"" + value + "\"}").getBytes(UTF_8)); + servlet.doPost(request, response); } - Assert.assertTrue(sb.toString().contains("null")); - httpUrlConnection.disconnect(); + return response; } -} + private static String errorMessage(MockHttpServletResponse response) throws Exception { + assertEquals(200, response.getStatus()); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(1, body.size()); + return body.getString("Error"); + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServletTest.java b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServletTest.java new file mode 100644 index 00000000000..a8810114f82 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionInfoByIdSolidityServletTest.java @@ -0,0 +1,135 @@ +package org.tron.core.services.http.solidity; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.Collection; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.util.ReflectionTestUtils; +import org.tron.common.utils.ByteArray; +import org.tron.core.Wallet; +import org.tron.core.config.args.Args; +import org.tron.json.JSONObject; +import org.tron.protos.Protocol.TransactionInfo; + +@RunWith(Parameterized.class) +public class GetTransactionInfoByIdSolidityServletTest { + + private static final String TRANSACTION_ID = + "309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef213f2c55225a8bd2"; + private static final ByteString TRANSACTION_ID_BYTES = + ByteString.copyFrom(ByteArray.fromHexString(TRANSACTION_ID)); + + @Parameter + public String method; + + private GetTransactionInfoByIdSolidityServlet servlet; + private Wallet wallet; + private long savedMaxMessageSize; + + @Parameters(name = "{0}") + public static Collection methods() { + return Arrays.asList(new Object[][] {{"GET"}, {"POST"}}); + } + + @Before + public void setUp() { + savedMaxMessageSize = Args.getInstance().getHttpMaxMessageSize(); + Args.getInstance().setHttpMaxMessageSize(1024); + servlet = new GetTransactionInfoByIdSolidityServlet(); + wallet = mock(Wallet.class); + ReflectionTestUtils.setField(servlet, "wallet", wallet); + } + + @After + public void tearDown() { + Args.getInstance().setHttpMaxMessageSize(savedMaxMessageSize); + } + + @Test + public void walletFailureReturnsSanitizedJson() throws Exception { + when(wallet.getTransactionInfoById(TRANSACTION_ID_BYTES)) + .thenThrow(new NullPointerException("internal transaction store detail")); + + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals("internal server error", errorMessage(response)); + verify(wallet).getTransactionInfoById(TRANSACTION_ID_BYTES); + } + + @Test + public void invalidHexReturnsJsonWithoutCallingWallet() throws Exception { + MockHttpServletResponse response = request("zz"); + + String message = errorMessage(response); + if ("GET".equals(method)) { + assertEquals("internal server error", message); + } else { + assertTrue(message.matches("\\d+:\\d+: INVALID hex String")); + } + verifyNoInteractions(wallet); + } + + @Test + public void missingTransactionKeepsEmptyObject() throws Exception { + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals(200, response.getStatus()); + assertEquals("{}", response.getContentAsString().trim()); + verify(wallet).getTransactionInfoById(TRANSACTION_ID_BYTES); + } + + @Test + public void successfulLookupKeepsTransactionInfo() throws Exception { + TransactionInfo info = TransactionInfo.newBuilder() + .setId(TRANSACTION_ID_BYTES).setFee(7).setBlockNumber(123).build(); + when(wallet.getTransactionInfoById(TRANSACTION_ID_BYTES)).thenReturn(info); + + MockHttpServletResponse response = request(TRANSACTION_ID); + + assertEquals(200, response.getStatus()); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(3, body.size()); + assertEquals(TRANSACTION_ID, body.getString("id")); + assertEquals(7L, body.getLongValue("fee")); + assertEquals(123L, body.getLongValue("blockNumber")); + verify(wallet).getTransactionInfoById(TRANSACTION_ID_BYTES); + } + + private MockHttpServletResponse request(String value) throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(method, + "/walletsolidity/gettransactioninfobyid"); + MockHttpServletResponse response = new MockHttpServletResponse(); + if ("GET".equals(method)) { + request.setParameter("value", value); + servlet.doGet(request, response); + } else { + request.setContentType("application/json"); + request.setContent(("{\"value\":\"" + value + "\"}").getBytes(UTF_8)); + servlet.doPost(request, response); + } + return response; + } + + private static String errorMessage(MockHttpServletResponse response) throws Exception { + assertEquals(200, response.getStatus()); + JSONObject body = JSONObject.parseObject(response.getContentAsString()); + assertEquals(1, body.size()); + return body.getString("Error"); + } +} diff --git a/framework/src/test/java/org/tron/core/services/jsonrpc/JsonRpcServletTest.java b/framework/src/test/java/org/tron/core/services/jsonrpc/JsonRpcServletTest.java index d6c843b5aea..bbba8ea3d46 100644 --- a/framework/src/test/java/org/tron/core/services/jsonrpc/JsonRpcServletTest.java +++ b/framework/src/test/java/org/tron/core/services/jsonrpc/JsonRpcServletTest.java @@ -12,6 +12,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import com.googlecode.jsonrpc4j.JsonRpcServer; import java.io.IOException; import java.io.InputStream; @@ -415,6 +417,40 @@ public void tooManyTokens_returnsParseError() throws Exception { message.contains("Token count") && message.contains("exceeds the maximum allowed")); } + @Test + public void batchResponse_preservesResultsWithinByteLimit() throws Exception { + CommonParameter.getInstance().jsonRpcMaxBatchSize = 2; + ObjectNode scalarResponse = MAPPER.createObjectNode(); + scalarResponse.put("jsonrpc", "2.0"); + scalarResponse.put("result", "ok"); + scalarResponse.put("id", 41); + ObjectNode arrayResponse = MAPPER.createObjectNode(); + arrayResponse.put("jsonrpc", "2.0"); + ArrayNode result = arrayResponse.putArray("result"); + result.add(0).add(1).add(2); + arrayResponse.put("id", 42); + byte[] scalarBytes = MAPPER.writeValueAsBytes(scalarResponse); + byte[] arrayBytes = MAPPER.writeValueAsBytes(arrayResponse); + // Include the batch brackets and comma; the response fits the byte limit exactly. + CommonParameter.getInstance().jsonRpcMaxResponseSize = + scalarBytes.length + arrayBytes.length + 3; + doAnswer(inv -> { + InputStream in = inv.getArgument(0); + OutputStream out = inv.getArgument(1); + JsonNode request = MAPPER.readTree(in); + out.write(request.get("id").asInt() == 41 ? scalarBytes : arrayBytes); + return 0; + }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); + + MockHttpServletResponse resp = doPost("[{\"id\":41},{\"id\":42}]"); + assertEquals(200, resp.getStatus()); + JsonNode body = MAPPER.readTree(resp.getContentAsByteArray()); + assertTrue(body.isArray()); + assertEquals(2, body.size()); + assertEquals(scalarResponse, body.get(0)); + assertEquals(arrayResponse, body.get(1)); + } + // --- helpers --- private MockHttpServletResponse doPost(String body) throws Exception { diff --git a/framework/src/test/java/org/tron/core/vm/OperationRegistryTest.java b/framework/src/test/java/org/tron/core/vm/OperationRegistryTest.java new file mode 100644 index 00000000000..b6568f8a862 --- /dev/null +++ b/framework/src/test/java/org/tron/core/vm/OperationRegistryTest.java @@ -0,0 +1,142 @@ +package org.tron.core.vm; + +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; + +import org.junit.Test; +import org.tron.core.vm.config.VMConfig; + +public class OperationRegistryTest { + + @Test + public void constantAndTransactionExecutionsUseDedicatedTables() { + JumpTable transactionTable = OperationRegistry.prepareAndGetTable(false); + JumpTable constantCallTable = OperationRegistry.prepareAndGetTable(true); + + assertNotSame(transactionTable, constantCallTable); + assertSame(transactionTable, OperationRegistry.getTable(false)); + assertSame(constantCallTable, OperationRegistry.getTable(true)); + } + + @Test + public void transactionExecutionsReuseTable() { + JumpTable first = OperationRegistry.prepareAndGetTable(false); + JumpTable second = OperationRegistry.prepareAndGetTable(false); + + assertSame(first, second); + } + + @Test + public void constantExecutionsReuseTable() { + JumpTable first = OperationRegistry.prepareAndGetTable(true); + JumpTable second = OperationRegistry.prepareAndGetTable(true); + + assertSame(first, second); + } + + @Test + public void constantAdjustmentsDoNotMutateTransactionTable() { + boolean previousHigherLimit = VMConfig.allowHigherLimitForMaxCpuTimeOfOneTx(); + JumpTable transactionTable = OperationRegistry.getTable(false); + JumpTable constantCallTable = OperationRegistry.getTable(true); + try { + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(0); + OperationRegistry.adjustMemOperations(transactionTable); + OperationRegistry.adjustMemOperations(constantCallTable); + Operation transactionMload = transactionTable.get(Op.MLOAD); + Operation constantMload = constantCallTable.get(Op.MLOAD); + + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(1); + OperationRegistry.adjustMemOperations(constantCallTable); + + assertSame(transactionMload, transactionTable.get(Op.MLOAD)); + assertNotSame(constantMload, constantCallTable.get(Op.MLOAD)); + } finally { + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(previousHigherLimit ? 1 : 0); + OperationRegistry.adjustMemOperations(transactionTable); + OperationRegistry.adjustMemOperations(constantCallTable); + } + } + + @Test + public void adjustedOperationsReuseCachedVariants() { + boolean previousHigherLimit = VMConfig.allowHigherLimitForMaxCpuTimeOfOneTx(); + boolean previousEnergyAdjustment = VMConfig.allowEnergyAdjustment(); + boolean previousOsaka = VMConfig.allowTvmOsaka(); + boolean previousSelfdestructRestriction = VMConfig.allowTvmSelfdestructRestriction(); + JumpTable table = OperationRegistry.newTronV15OperationSet(); + + Operation defaultMload = table.get(Op.MLOAD); + Operation defaultMstore = table.get(Op.MSTORE); + Operation defaultMstore8 = table.get(Op.MSTORE8); + Operation defaultVoteWitness = table.get(Op.VOTEWITNESS); + Operation defaultSuicide = table.get(Op.SUICIDE); + + try { + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(1); + VMConfig.initAllowEnergyAdjustment(1); + VMConfig.initAllowTvmOsaka(0); + VMConfig.initAllowTvmSelfdestructRestriction(0); + adjustOperations(table); + + Operation adjustedMload = table.get(Op.MLOAD); + Operation adjustedMstore = table.get(Op.MSTORE); + Operation adjustedMstore8 = table.get(Op.MSTORE8); + Operation adjustedVoteWitness = table.get(Op.VOTEWITNESS); + Operation adjustedSuicide = table.get(Op.SUICIDE); + + assertNotSame(defaultMload, adjustedMload); + assertNotSame(defaultMstore, adjustedMstore); + assertNotSame(defaultMstore8, adjustedMstore8); + assertNotSame(defaultVoteWitness, adjustedVoteWitness); + assertNotSame(defaultSuicide, adjustedSuicide); + + adjustOperations(table); + assertSame(adjustedMload, table.get(Op.MLOAD)); + assertSame(adjustedMstore, table.get(Op.MSTORE)); + assertSame(adjustedMstore8, table.get(Op.MSTORE8)); + assertSame(adjustedVoteWitness, table.get(Op.VOTEWITNESS)); + assertSame(adjustedSuicide, table.get(Op.SUICIDE)); + + VMConfig.initAllowTvmOsaka(1); + VMConfig.initAllowTvmSelfdestructRestriction(1); + adjustOperations(table); + + Operation osakaVoteWitness = table.get(Op.VOTEWITNESS); + Operation restrictedSuicide = table.get(Op.SUICIDE); + assertNotSame(adjustedVoteWitness, osakaVoteWitness); + assertNotSame(adjustedSuicide, restrictedSuicide); + + adjustOperations(table); + assertSame(adjustedMload, table.get(Op.MLOAD)); + assertSame(adjustedMstore, table.get(Op.MSTORE)); + assertSame(adjustedMstore8, table.get(Op.MSTORE8)); + assertSame(osakaVoteWitness, table.get(Op.VOTEWITNESS)); + assertSame(restrictedSuicide, table.get(Op.SUICIDE)); + + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(0); + VMConfig.initAllowEnergyAdjustment(0); + VMConfig.initAllowTvmOsaka(0); + VMConfig.initAllowTvmSelfdestructRestriction(0); + adjustOperations(table); + + assertSame(defaultMload, table.get(Op.MLOAD)); + assertSame(defaultMstore, table.get(Op.MSTORE)); + assertSame(defaultMstore8, table.get(Op.MSTORE8)); + assertSame(defaultVoteWitness, table.get(Op.VOTEWITNESS)); + assertSame(defaultSuicide, table.get(Op.SUICIDE)); + } finally { + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx(previousHigherLimit ? 1 : 0); + VMConfig.initAllowEnergyAdjustment(previousEnergyAdjustment ? 1 : 0); + VMConfig.initAllowTvmOsaka(previousOsaka ? 1 : 0); + VMConfig.initAllowTvmSelfdestructRestriction( + previousSelfdestructRestriction ? 1 : 0); + } + } + + private static void adjustOperations(JumpTable table) { + OperationRegistry.adjustMemOperations(table); + OperationRegistry.adjustVoteWitness(table); + OperationRegistry.adjustSelfdestruct(table); + } +} diff --git a/framework/src/test/java/org/tron/core/vm/nativecontract/StakeV2AfterSelfDestructTest.java b/framework/src/test/java/org/tron/core/vm/nativecontract/StakeV2AfterSelfDestructTest.java new file mode 100644 index 00000000000..a3c59019b6d --- /dev/null +++ b/framework/src/test/java/org/tron/core/vm/nativecontract/StakeV2AfterSelfDestructTest.java @@ -0,0 +1,186 @@ +package org.tron.core.vm.nativecontract; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.core.config.Parameter.ForkBlockVersionEnum.VERSION_4_8_2_2; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +import com.google.protobuf.ByteString; +import org.junit.Assert; +import org.junit.Test; +import org.junit.function.ThrowingRunnable; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.ForkController; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.vm.nativecontract.param.CancelAllUnfreezeV2Param; +import org.tron.core.vm.nativecontract.param.FreezeBalanceV2Param; +import org.tron.core.vm.nativecontract.param.UnfreezeBalanceV2Param; +import org.tron.core.vm.nativecontract.param.WithdrawExpireUnfreezeParam; +import org.tron.core.vm.program.Program.OutOfTimeException; +import org.tron.core.vm.repository.Repository; +import org.tron.protos.Protocol; +import org.tron.protos.contract.Common.ResourceCode; + +public class StakeV2AfterSelfDestructTest { + + private static final long NOW = 1_000L; + + @Test + public void freezeAfterSelfDestructIsForkGated() throws Exception { + byte[] ownerAddress = address(1); + AccountCapsule owner = account(ownerAddress, 0, 0); + owner.setBalance(TRX_PRECISION); + + Repository repository = mock(Repository.class); + DynamicPropertiesStore dynamicStore = mock(DynamicPropertiesStore.class); + when(repository.getDynamicPropertiesStore()).thenReturn(dynamicStore); + when(repository.getAccount(ownerAddress)).thenReturn(owner); + when(repository.isSelfDestructed(ownerAddress)).thenReturn(true); + + FreezeBalanceV2Param param = new FreezeBalanceV2Param(); + param.setOwnerAddress(ownerAddress); + param.setFrozenBalance(TRX_PRECISION); + param.setResourceType(BANDWIDTH); + FreezeBalanceV2Processor processor = new FreezeBalanceV2Processor(); + + ForkController forkController = mock(ForkController.class); + try (MockedStatic fork = Mockito.mockStatic(ForkController.class)) { + fork.when(ForkController::instance).thenReturn(forkController); + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(false); + processor.validate(param, repository); + + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(true); + assertFreezeV2Timeout(() -> processor.validate(param, repository)); + } + } + + @Test + public void invalidDelegatedBalancesBlockWithdrawAndCancelAfterFork() throws Exception { + byte[] ownerAddress = address(1); + Repository repository = mock(Repository.class); + DynamicPropertiesStore dynamicStore = mock(DynamicPropertiesStore.class); + when(repository.getDynamicPropertiesStore()).thenReturn(dynamicStore); + when(dynamicStore.getLatestBlockHeaderTimestamp()).thenReturn(NOW); + + WithdrawExpireUnfreezeParam withdrawParam = new WithdrawExpireUnfreezeParam(); + withdrawParam.setOwnerAddress(ownerAddress); + WithdrawExpireUnfreezeProcessor withdrawProcessor = + new WithdrawExpireUnfreezeProcessor(); + CancelAllUnfreezeV2Param cancelParam = new CancelAllUnfreezeV2Param(); + cancelParam.setOwnerAddress(ownerAddress); + CancelAllUnfreezeV2Processor cancelProcessor = new CancelAllUnfreezeV2Processor(); + + ForkController forkController = mock(ForkController.class); + try (MockedStatic fork = Mockito.mockStatic(ForkController.class)) { + fork.when(ForkController::instance).thenReturn(forkController); + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(false); + when(repository.getAccount(ownerAddress)).thenReturn(account(ownerAddress, -1, 0)); + withdrawProcessor.validate(withdrawParam, repository); + cancelProcessor.validate(cancelParam, repository); + when(repository.getAccount(ownerAddress)).thenReturn(account(ownerAddress, 0, -1)); + withdrawProcessor.validate(withdrawParam, repository); + cancelProcessor.validate(cancelParam, repository); + + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(true); + when(repository.getAccount(ownerAddress)).thenReturn(account(ownerAddress, -1, 0)); + assertInvalidDelegatedV2Timeout( + () -> withdrawProcessor.validate(withdrawParam, repository)); + assertInvalidDelegatedV2Timeout( + () -> cancelProcessor.validate(cancelParam, repository)); + when(repository.getAccount(ownerAddress)).thenReturn(account(ownerAddress, 0, -1)); + assertInvalidDelegatedV2Timeout( + () -> withdrawProcessor.validate(withdrawParam, repository)); + assertInvalidDelegatedV2Timeout( + () -> cancelProcessor.validate(cancelParam, repository)); + } + } + + @Test + public void invalidDelegatedBalancesBlockUnfreezeAfterFork() throws Exception { + byte[] ownerAddress = address(1); + Repository repository = mock(Repository.class); + DynamicPropertiesStore dynamicStore = mock(DynamicPropertiesStore.class); + when(repository.getDynamicPropertiesStore()).thenReturn(dynamicStore); + when(dynamicStore.getLatestBlockHeaderTimestamp()).thenReturn(NOW); + + UnfreezeBalanceV2Param bandwidthParam = unfreezeParam(ownerAddress, BANDWIDTH); + UnfreezeBalanceV2Param energyParam = unfreezeParam(ownerAddress, ENERGY); + UnfreezeBalanceV2Processor processor = new UnfreezeBalanceV2Processor(); + + ForkController forkController = mock(ForkController.class); + try (MockedStatic fork = Mockito.mockStatic(ForkController.class)) { + fork.when(ForkController::instance).thenReturn(forkController); + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(false); + when(repository.getAccount(ownerAddress)).thenReturn( + accountWithFrozenV2(ownerAddress, -1, 0, BANDWIDTH)); + processor.validate(bandwidthParam, repository); + when(repository.getAccount(ownerAddress)).thenReturn( + accountWithFrozenV2(ownerAddress, 0, -1, ENERGY)); + processor.validate(energyParam, repository); + + when(forkController.pass(VERSION_4_8_2_2)).thenReturn(true); + when(repository.getAccount(ownerAddress)).thenReturn( + accountWithFrozenV2(ownerAddress, -1, 0, BANDWIDTH)); + assertInvalidDelegatedV2Timeout( + () -> processor.validate(bandwidthParam, repository)); + when(repository.getAccount(ownerAddress)).thenReturn( + accountWithFrozenV2(ownerAddress, 0, -1, ENERGY)); + assertInvalidDelegatedV2Timeout(() -> processor.validate(energyParam, repository)); + } + } + + private static AccountCapsule account(byte[] address, long bandwidth, long energy) { + Protocol.Account.AccountResource resource = Protocol.Account.AccountResource.newBuilder() + .setDelegatedFrozenV2BalanceForEnergy(energy) + .build(); + Protocol.Account account = Protocol.Account.newBuilder() + .setAddress(ByteString.copyFrom(address)) + .setDelegatedFrozenV2BalanceForBandwidth(bandwidth) + .setAccountResource(resource) + .build(); + return new AccountCapsule(account); + } + + private static AccountCapsule accountWithFrozenV2( + byte[] address, long bandwidth, long energy, ResourceCode resourceCode) { + AccountCapsule accountCapsule = account(address, bandwidth, energy); + if (resourceCode == BANDWIDTH) { + accountCapsule.addFrozenBalanceForBandwidthV2(TRX_PRECISION); + } else { + accountCapsule.addFrozenBalanceForEnergyV2(TRX_PRECISION); + } + return accountCapsule; + } + + private static UnfreezeBalanceV2Param unfreezeParam( + byte[] ownerAddress, ResourceCode resourceCode) { + UnfreezeBalanceV2Param param = new UnfreezeBalanceV2Param(); + param.setOwnerAddress(ownerAddress); + param.setResourceType(resourceCode); + param.setUnfreezeBalance(TRX_PRECISION); + return param; + } + + private static byte[] address(int suffix) { + byte[] address = new byte[21]; + address[0] = DecodeUtil.addressPreFixByte; + address[address.length - 1] = (byte) suffix; + return address; + } + + private static void assertFreezeV2Timeout(ThrowingRunnable runnable) { + OutOfTimeException exception = Assert.assertThrows(OutOfTimeException.class, runnable); + Assert.assertEquals( + "CPU timeout for FreezeBalanceV2 after SELFDESTRUCT", exception.getMessage()); + } + + private static void assertInvalidDelegatedV2Timeout(ThrowingRunnable runnable) { + OutOfTimeException exception = Assert.assertThrows(OutOfTimeException.class, runnable); + Assert.assertEquals("CPU timeout for invalid delegated V2 balance", exception.getMessage()); + } +} diff --git a/framework/src/test/java/org/tron/core/vm/repository/RepositoryImplSelfDestructTest.java b/framework/src/test/java/org/tron/core/vm/repository/RepositoryImplSelfDestructTest.java new file mode 100644 index 00000000000..10131a06595 --- /dev/null +++ b/framework/src/test/java/org/tron/core/vm/repository/RepositoryImplSelfDestructTest.java @@ -0,0 +1,36 @@ +package org.tron.core.vm.repository; + +import org.junit.Assert; +import org.junit.Test; + +public class RepositoryImplSelfDestructTest { + + private static final byte[] ADDRESS = new byte[] {1}; + + @Test + public void committedSelfDestructMarkerIsVisibleToParentAndSibling() { + Repository root = RepositoryImpl.createRoot(null); + Repository child = root.newRepositoryChild(); + + child.markSelfDestruct(ADDRESS); + Assert.assertTrue(child.isSelfDestructed(ADDRESS)); + Assert.assertFalse(root.isSelfDestructed(ADDRESS)); + + child.commit(); + Assert.assertTrue(root.isSelfDestructed(ADDRESS)); + Assert.assertTrue(root.newRepositoryChild().isSelfDestructed(ADDRESS)); + } + + @Test + public void nestedMarkerDoesNotLeakWhenOuterCallIsReverted() { + Repository root = RepositoryImpl.createRoot(null); + Repository outerCall = root.newRepositoryChild(); + Repository nestedCall = outerCall.newRepositoryChild(); + + nestedCall.markSelfDestruct(ADDRESS); + nestedCall.commit(); + + Assert.assertTrue(outerCall.isSelfDestructed(ADDRESS)); + Assert.assertFalse(root.isSelfDestructed(ADDRESS)); + } +} diff --git a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java index 08de83ca8bf..efa60139b12 100644 --- a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java @@ -14,6 +14,7 @@ import java.util.Optional; import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; @@ -106,6 +107,7 @@ public class SendCoinShieldTest extends BaseTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network"; + private long previousAllowShieldedTransaction; @Resource private Wallet wallet; @@ -130,6 +132,8 @@ public static void initZksnarkParams() { */ @Before public void init() { + previousAllowShieldedTransaction = dbManager.getDynamicPropertiesStore() + .getAllowShieldedTransaction(); if (init) { return; } @@ -155,6 +159,12 @@ public void init() { init = true; } + @After + public void restoreAllowShieldedTransaction() { + dbManager.getDynamicPropertiesStore() + .saveAllowShieldedTransaction(previousAllowShieldedTransaction); + } + private void addZeroValueOutputNote(ZenTransactionBuilder builder) throws ZksnarkException { SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); diff --git a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java index 5854b731e97..e62396bc046 100755 --- a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java @@ -8,7 +8,6 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; -import java.lang.reflect.Field; import java.security.SignatureException; import java.util.Arrays; import java.util.HashSet; @@ -21,6 +20,7 @@ import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; @@ -47,7 +47,6 @@ import org.tron.common.zksnark.LibrustzcashParam.OutputProofParams; import org.tron.common.zksnark.LibrustzcashParam.SpendSigParams; import org.tron.consensus.dpos.DposSlot; -import org.tron.consensus.dpos.DposTask; import org.tron.core.Wallet; import org.tron.core.actuator.Actuator; import org.tron.core.actuator.ActuatorCreator; @@ -126,6 +125,7 @@ public class ShieldedReceiveTest extends BaseTest { "librustzcashSaplingCheckSpend error", "Rt is invalid." )); + private long previousAllowShieldedTransaction; private static final String FROM_ADDRESS; private static final String ADDRESS_ONE_PRIVATE_KEY; @@ -143,13 +143,11 @@ public class ShieldedReceiveTest extends BaseTest { @Resource private ConsensusService consensusService; @Resource - private DposTask dposTask; - @Resource private Wallet wallet; @Resource private DposSlot dposSlot; - private static boolean init; + private static boolean consensusScheduleInitialized; static { Args.setParam(new String[] {"--output-directory", dbPath(), "-w"}, SHIELD_CONF); @@ -167,14 +165,21 @@ public static void initZksnarkParams() { */ @Before public void init() { + previousAllowShieldedTransaction = chainBaseManager.getDynamicPropertiesStore() + .getAllowShieldedTransaction(); if (init) { return; } - consensusService.start(); chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(10_000_000_000L); init = true; } + @After + public void restoreAllowShieldedTransaction() { + chainBaseManager.getDynamicPropertiesStore() + .saveAllowShieldedTransaction(previousAllowShieldedTransaction); + } + private static byte[] randomUint256() { return org.tron.keystore.Wallet.generateRandomBytes(32); } @@ -254,9 +259,28 @@ private void updateTotalShieldedPoolValue(long valueBalance) { @Test public void testIsMining() { + initializeActiveWitnessSchedule(); Assert.assertTrue(wallet.isMining()); } + private void initializeActiveWitnessSchedule() { + synchronized (ShieldedReceiveTest.class) { + if (consensusScheduleInitialized) { + return; + } + boolean started = false; + try { + consensusService.start(); + started = true; + } finally { + if (started) { + consensusService.stop(); + } + } + consensusScheduleInitialized = true; + } + } + /* * test of change ShieldedTransactionFee proposal */ @@ -2407,144 +2431,134 @@ public void pushSameSkAndScanAndSpend() throws Exception { assert ecKey != null; byte[] witnessAddress = ecKey.getAddress(); WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); - // Stop the consensus task before modifying the witness schedule: DposTask uses the same - // localwitness key and would otherwise race to produce blocks at the same slot, - // triggering fork resolution and making the test slow. - consensusService.stop(); - try { - chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); - - long time = nextScheduledTime(witnessCapsule.getAddress()); - Block block = getSignedBlock(witnessCapsule.getAddress(), time, privateKey); - dbManager.pushBlock(new BlockCapsule(block)); - - //create transactions - chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1); - chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(1000 * 1000000L); - ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet); - - // generate spend proof - SpendingKey sk = SpendingKey - .decode("ff2c06269315333a9207f817d2eca0ac555ca8f90196976324c7756504e7c9ee"); - ExpandedSpendingKey expsk = sk.expandedSpendingKey(); - byte[] senderOvk = expsk.getOvk(); - PaymentAddress address = sk.defaultAddress(); - Note note = new Note(address, 1000 * 1000000L); - IncrementalMerkleVoucherContainer voucher = createSimpleMerkleVoucherContainer(note.cm()); - byte[] anchor = voucher.root().getContent().toByteArray(); - chainBaseManager.getMerkleContainer() - .putMerkleTreeIntoStore(anchor, voucher.getVoucherCapsule().getTree()); - builder.addSpend(expsk, note, anchor, voucher); - - // generate output proof - SpendingKey sk2 = SpendingKey.random(); - FullViewingKey fullViewingKey = sk2.fullViewingKey(); - IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - - byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); - - //send coin to 2 different address generated by same sk - DiversifierT d1 = DiversifierT.random(); - PaymentAddress paymentAddress1 = incomingViewingKey.address(d1).get(); - builder.addOutput(senderOvk, paymentAddress1, - (1000 * 1000000L - wallet.getShieldedTransactionFee()) / 2, memo); - - DiversifierT d2 = DiversifierT.random(); - PaymentAddress paymentAddress2 = incomingViewingKey.address(d2).get(); - builder.addOutput(senderOvk, paymentAddress2, - (1000 * 1000000L - wallet.getShieldedTransactionFee()) / 2, memo); + // Initialize the same schedule as DPoS startup without starting its producer thread. + // Manual block production below therefore cannot race the background producer. + initializeActiveWitnessSchedule(); + chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); - TransactionCapsule transactionCap = builder.build(); + long time = nextScheduledTime(witnessCapsule.getAddress()); + Block block = getSignedBlock(witnessCapsule.getAddress(), time, privateKey); + dbManager.pushBlock(new BlockCapsule(block)); - byte[] trxId = transactionCap.getTransactionId().getBytes(); - boolean ok = dbManager.pushTransaction(transactionCap); - Assert.assertTrue(ok); - - Thread.sleep(500); - //package transaction to block - long expectedBlockNum = chainBaseManager.getDynamicPropertiesStore() - .getLatestBlockHeaderNumber() + 1; - block = getSignedBlock(witnessCapsule.getAddress(), - nextScheduledTime(witnessCapsule.getAddress()), privateKey); - dbManager.pushBlock(new BlockCapsule(block)); - - BlockCapsule blockCapsule3 = new BlockCapsule(wallet.getNowBlock()); - Assert.assertEquals("unexpected block number", expectedBlockNum, blockCapsule3.getNum()); - - block = getSignedBlock(witnessCapsule.getAddress(), - nextScheduledTime(witnessCapsule.getAddress()), privateKey); - dbManager.pushBlock(new BlockCapsule(block)); - - // scan note by ivk - byte[] receiverIvk = incomingViewingKey.getValue(); - DecryptNotes notes1 = wallet.scanNoteByIvk(0, 100, receiverIvk); - Assert.assertEquals(2, notes1.getNoteTxsCount()); - - // scan note by ivk and mark - DecryptNotesMarked notes3 = wallet.scanAndMarkNoteByIvk(0, 100, receiverIvk, - fullViewingKey.getAk(), fullViewingKey.getNk()); - Assert.assertEquals(2, notes3.getNoteTxsCount()); - - // scan note by ovk - DecryptNotes notes2 = wallet.scanNoteByOvk(0, 100, senderOvk); - Assert.assertEquals(2, notes2.getNoteTxsCount()); - - // to spend received note above. - ZenTransactionBuilder builder2 = new ZenTransactionBuilder(wallet); - - //query merkleinfo - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - for (int i = 0; i < notes1.getNoteTxsCount(); i++) { - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(trxId)); - outPointBuild.setIndex(i); - request.addOutPoints(outPointBuild.build()); - } - request.setBlockNum(1); - IncrementalMerkleVoucherInfo merkleVoucherInfo = wallet - .getMerkleTreeVoucherInfo(request.build()); - - //build spend proof. allow only one note in spend - ExpandedSpendingKey expsk2 = sk2.expandedSpendingKey(); - for (int i = 0; i < 1; i++) { - org.tron.api.GrpcAPI.Note grpcNote = notes1.getNoteTxs(i).getNote(); - PaymentAddress paymentAddress = KeyIo.decodePaymentAddress(grpcNote.getPaymentAddress()); - Note note2 = new Note(paymentAddress.getD(), - paymentAddress.getPkD(), - grpcNote.getValue(), - grpcNote.getRcm().toByteArray() - ); - - IncrementalMerkleVoucherContainer voucher2 = - new IncrementalMerkleVoucherContainer( - new IncrementalMerkleVoucherCapsule(merkleVoucherInfo.getVouchers(i))); - byte[] anchor2 = voucher2.root().getContent().toByteArray(); - builder2.addSpend(expsk2, note2, anchor2, voucher2); - } + //create transactions + chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1); + chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(1000 * 1000000L); + ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet); + + // generate spend proof + SpendingKey sk = SpendingKey + .decode("ff2c06269315333a9207f817d2eca0ac555ca8f90196976324c7756504e7c9ee"); + ExpandedSpendingKey expsk = sk.expandedSpendingKey(); + byte[] senderOvk = expsk.getOvk(); + PaymentAddress address = sk.defaultAddress(); + Note note = new Note(address, 1000 * 1000000L); + IncrementalMerkleVoucherContainer voucher = createSimpleMerkleVoucherContainer(note.cm()); + byte[] anchor = voucher.root().getContent().toByteArray(); + chainBaseManager.getMerkleContainer() + .putMerkleTreeIntoStore(anchor, voucher.getVoucherCapsule().getTree()); + builder.addSpend(expsk, note, anchor, voucher); + + // generate output proof + SpendingKey sk2 = SpendingKey.random(); + FullViewingKey fullViewingKey = sk2.fullViewingKey(); + IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); + + byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); + + //send coin to 2 different address generated by same sk + DiversifierT d1 = DiversifierT.random(); + PaymentAddress paymentAddress1 = incomingViewingKey.address(d1).get(); + builder.addOutput(senderOvk, paymentAddress1, + (1000 * 1000000L - wallet.getShieldedTransactionFee()) / 2, memo); + + DiversifierT d2 = DiversifierT.random(); + PaymentAddress paymentAddress2 = incomingViewingKey.address(d2).get(); + builder.addOutput(senderOvk, paymentAddress2, + (1000 * 1000000L - wallet.getShieldedTransactionFee()) / 2, memo); - //build output proof - SpendingKey sk3 = SpendingKey.random(); - FullViewingKey fvk3 = sk3.fullViewingKey(); - IncomingViewingKey ivk3 = fvk3.inViewingKey(); - - DiversifierT d3 = DiversifierT.random(); - PaymentAddress paymentAddress3 = incomingViewingKey.address(d3).get(); - byte[] memo3 = org.tron.keystore.Wallet.generateRandomBytes(512); - builder2.addOutput(expsk2.getOvk(), paymentAddress3, - (1000 * 1000000L - wallet.getShieldedTransactionFee()) / 2 - wallet - .getShieldedTransactionFee(), memo3); - - TransactionCapsule transactionCap2 = builder2.build(); - boolean ok2 = dbManager.pushTransaction(transactionCap2); - Assert.assertTrue(ok2); - } finally { - // DposTask.init() does not reset isRunning (it stays false after stop()), so force it back - // to true via reflection before restarting. - Field isRunning = DposTask.class.getDeclaredField("isRunning"); - isRunning.setAccessible(true); - isRunning.set(dposTask, true); - consensusService.start(); + TransactionCapsule transactionCap = builder.build(); + + byte[] trxId = transactionCap.getTransactionId().getBytes(); + boolean ok = dbManager.pushTransaction(transactionCap); + Assert.assertTrue(ok); + + Thread.sleep(500); + //package transaction to block + long expectedBlockNum = chainBaseManager.getDynamicPropertiesStore() + .getLatestBlockHeaderNumber() + 1; + block = getSignedBlock(witnessCapsule.getAddress(), + nextScheduledTime(witnessCapsule.getAddress()), privateKey); + dbManager.pushBlock(new BlockCapsule(block)); + + BlockCapsule blockCapsule3 = new BlockCapsule(wallet.getNowBlock()); + Assert.assertEquals("unexpected block number", expectedBlockNum, blockCapsule3.getNum()); + + block = getSignedBlock(witnessCapsule.getAddress(), + nextScheduledTime(witnessCapsule.getAddress()), privateKey); + dbManager.pushBlock(new BlockCapsule(block)); + + // scan note by ivk + byte[] receiverIvk = incomingViewingKey.getValue(); + DecryptNotes notes1 = wallet.scanNoteByIvk(0, 100, receiverIvk); + Assert.assertEquals(2, notes1.getNoteTxsCount()); + + // scan note by ivk and mark + DecryptNotesMarked notes3 = wallet.scanAndMarkNoteByIvk(0, 100, receiverIvk, + fullViewingKey.getAk(), fullViewingKey.getNk()); + Assert.assertEquals(2, notes3.getNoteTxsCount()); + + // scan note by ovk + DecryptNotes notes2 = wallet.scanNoteByOvk(0, 100, senderOvk); + Assert.assertEquals(2, notes2.getNoteTxsCount()); + + // to spend received note above. + ZenTransactionBuilder builder2 = new ZenTransactionBuilder(wallet); + + //query merkleinfo + OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); + for (int i = 0; i < notes1.getNoteTxsCount(); i++) { + OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); + outPointBuild.setHash(ByteString.copyFrom(trxId)); + outPointBuild.setIndex(i); + request.addOutPoints(outPointBuild.build()); + } + request.setBlockNum(1); + IncrementalMerkleVoucherInfo merkleVoucherInfo = wallet + .getMerkleTreeVoucherInfo(request.build()); + + //build spend proof. allow only one note in spend + ExpandedSpendingKey expsk2 = sk2.expandedSpendingKey(); + for (int i = 0; i < 1; i++) { + org.tron.api.GrpcAPI.Note grpcNote = notes1.getNoteTxs(i).getNote(); + PaymentAddress paymentAddress = KeyIo.decodePaymentAddress(grpcNote.getPaymentAddress()); + Note note2 = new Note(paymentAddress.getD(), + paymentAddress.getPkD(), + grpcNote.getValue(), + grpcNote.getRcm().toByteArray() + ); + + IncrementalMerkleVoucherContainer voucher2 = + new IncrementalMerkleVoucherContainer( + new IncrementalMerkleVoucherCapsule(merkleVoucherInfo.getVouchers(i))); + byte[] anchor2 = voucher2.root().getContent().toByteArray(); + builder2.addSpend(expsk2, note2, anchor2, voucher2); } + + //build output proof + SpendingKey sk3 = SpendingKey.random(); + FullViewingKey fvk3 = sk3.fullViewingKey(); + IncomingViewingKey ivk3 = fvk3.inViewingKey(); + + DiversifierT d3 = DiversifierT.random(); + PaymentAddress paymentAddress3 = incomingViewingKey.address(d3).get(); + byte[] memo3 = org.tron.keystore.Wallet.generateRandomBytes(512); + builder2.addOutput(expsk2.getOvk(), paymentAddress3, + (1000 * 1000000L - wallet.getShieldedTransactionFee()) / 2 - wallet + .getShieldedTransactionFee(), memo3); + + TransactionCapsule transactionCap2 = builder2.build(); + boolean ok2 = dbManager.pushTransaction(transactionCap2); + Assert.assertTrue(ok2); } // Returns the earliest timestamp at which witnessAddr is the DPoS-scheduled producer, diff --git a/framework/src/test/java/org/tron/json/JsonTest.java b/framework/src/test/java/org/tron/json/JsonTest.java index 081e51d5571..d38123bffdd 100644 --- a/framework/src/test/java/org/tron/json/JsonTest.java +++ b/framework/src/test/java/org/tron/json/JsonTest.java @@ -408,6 +408,55 @@ public void testJsonMapperHasConfiguredConstraints() { assertEquals((long) Constant.MAX_TOKEN_COUNT, sr.getMaxTokenCount()); } + @Test + public void testOutboundParseObjectPreservesCompatibility() { + for (String text : Arrays.asList(null, "", " \n\t", "null", "/* comment */ null")) { + assertNull(JSONObject.outboundParseObject(text)); + } + for (String text : Arrays.asList( + "{unquoted:'value', trailing:1,}", + "{a:+1,b:-2,c:.3,d:-.4,e:+.5,f:+6.,g:007}", + "{/* comment */a:'line1\n\tline2'} // trailing comment", + "{amount:1,amount:2,decimal:0.12345678901234567890123456789}", + "{large:9223372036854775808,missing:null,array:[{nested:true},false]}")) { + assertEquals(JSONObject.parseObject(text).toJSONString(), + JSONObject.outboundParseObject(text).toJSONString()); + } + assertEquals(new BigDecimal("0.12345678901234567890123456789"), + JSONObject.outboundParseObject("{value:0.12345678901234567890123456789}") + .getBigDecimal("value")); + } + + @Test + public void testOutboundParseObjectPreservesParseErrors() { + for (String text : Arrays.asList("[]", "1", "{a:abc}", "{} {}", "NULL", "{a:NaN}")) { + JSONException expected = assertThrows(JSONException.class, + () -> JSONObject.parseObject(text)); + JSONException actual = assertThrows(JSONException.class, + () -> JSONObject.outboundParseObject(text)); + assertEquals(expected.getMessage(), actual.getMessage()); + } + } + + @Test + public void testOutboundParseObjectPreservesArray() { + String text = "{\"values\":[0,1,2]}"; + JSONObject parsed = JSONObject.outboundParseObject(text); + JSONArray values = parsed.getJSONArray("values"); + assertEquals(3, values.size()); + assertEquals(Integer.valueOf(0), values.get(0)); + assertEquals(Integer.valueOf(2), values.get(2)); + assertEquals(text, parsed.toJSONString()); + } + + @Test + public void testOutboundParseObjectPreservesNestedObjects() { + String text = "{\"outer\":{\"inner\":{\"value\":1}}}"; + JSONObject parsed = JSONObject.outboundParseObject(text); + assertEquals(1, parsed.getJSONObject("outer").getJSONObject("inner").getIntValue("value")); + assertEquals(text, parsed.toJSONString()); + } + @Test public void testParseObjectRejectsOverDepth() { StringBuilder open = new StringBuilder(); diff --git a/framework/src/test/resources/config-shield.conf b/framework/src/test/resources/config-shield.conf index 1c185f8f82f..33f270bfa03 100644 --- a/framework/src/test/resources/config-shield.conf +++ b/framework/src/test/resources/config-shield.conf @@ -41,9 +41,6 @@ node { # trustNode = "ip:port" trustNode = "127.0.0.1:50051" - # expose extension api to public or not - walletExtensionApi = true - listen.port = 6666 # Number of validate sign thread, default availableProcessors / 2 diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index 6a3e641d5d6..a73c4715fe1 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -49,25 +49,25 @@ - - - + + + - - + + - - - + + + - - + + - - - + + + @@ -189,9 +189,9 @@ - - - + + + @@ -199,9 +199,9 @@ - - - + + + @@ -219,15 +219,15 @@ - - - + + + - - + + - - + + @@ -235,15 +235,15 @@ - - - + + + - - + + - - + + @@ -251,15 +251,15 @@ - - - + + + - - + + - - + + @@ -448,6 +448,14 @@ + + + + + + + + @@ -463,6 +471,11 @@ + + + + + @@ -1171,76 +1184,76 @@ - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + - - - + + + - - + + @@ -1251,18 +1264,18 @@ - - - + + + - - + + - - + + - - + + @@ -1528,14 +1541,6 @@ - - - - - - - - @@ -1684,11 +1689,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1710,36 +1741,9 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + @@ -1792,6 +1796,11 @@ + + + + + @@ -1985,6 +1994,14 @@ + + + + + + + + @@ -2408,6 +2425,14 @@ + + + + + + + + @@ -2424,6 +2449,14 @@ + + + + + + + + @@ -2448,6 +2481,11 @@ + + + + + @@ -2612,20 +2650,20 @@ - - - + + + - - + + - - - + + + - - + + @@ -2647,16 +2685,26 @@ - - - - - - + + + + + + + + + + + + + + + + diff --git a/p2p/.gitignore b/p2p/.gitignore new file mode 100644 index 00000000000..ebb224e762b --- /dev/null +++ b/p2p/.gitignore @@ -0,0 +1,2 @@ +# protobuf generated code (rebuilt by ./gradlew :p2p:generateProto) +src/main/java/org/tron/p2p/protos/ diff --git a/p2p/README.md b/p2p/README.md new file mode 100644 index 00000000000..a94c4587bd1 --- /dev/null +++ b/p2p/README.md @@ -0,0 +1,453 @@ +# p2p + +Peer discovery, connection management and DNS-based node lists for java-tron. + +> **Vendored from [tronprotocol/libp2p](https://github.com/tronprotocol/libp2p) +> v2.2.9.** It lives here as the `:p2p` Gradle module and is consumed as a +> project dependency, not as a published artifact — `:common` exposes it via +> `api project(":p2p")`. Upstream's own README follows, edited where +> internalizing changed the facts; treat this file as the module's docs rather +> than as a mirror of upstream. + +## Running it on its own + +`./gradlew :p2p:build` produces two jars: + +| | | +|---|---| +| `p2p-1.0.0.jar` | thin — what java-tron depends on, no `Main-Class` | +| `p2p-standalone.jar` | all dependencies bundled, `Main-Class` set to `StartApp` | + +Use the standalone one to drive the module without starting java-tron: + +```bash +./gradlew :p2p:buildStandaloneJar +java -jar p2p/build/libs/p2p-standalone.jar --help +``` + +`-PbinaryRelease=false` skips building it, matching `:framework` and `:plugins`. + +This module can run on its own, or be used as a library. + +# 1. Run independently + +command of start a p2p node: + +```bash +$ java -jar p2p/build/libs/p2p-standalone.jar [options] +``` + +available cli options: + +```bash +usage: available p2p discovery cli options: + -a,--active-nodes active node(s), + ip:port[,ip:port[...]] + -d,--discover enable p2p discover, 0/1, default 1 + -h,--help print help message + -M,--max-connection max connection number, int, default + 50 + -m,--min-connection min connection number, int, default 8 + -ma,--min-active-connection min active connection number, int, + default 2 + -p,--port UDP & TCP port, int, default 18888 + -s,--seed-nodes seed node(s), required, + ip:port[,ip:port[...]] + -t,--trust-ips trust ip(s), ip[,ip[...]] + -v,--version p2p version, int, default 1 + +available dns read cli options: + -u,--url-schemes dns url(s) to get nodes, url format + tree://{pubkey}@{domain}, url[,url[...]] + +available dns publish cli options: + --access-key-id access key id of aws or aliyun api, + required, string + --access-key-secret access key secret of aws or aliyun api, + required, string + --aliyun-dns-endpoint if server-type is aliyun, it's endpoint + of aws dns server, required, string + --aws-region if server-type is aws, it's region of + aws api, such as "eu-south-1", required, + string + --change-threshold change threshold of add and delete to + publish, optional, should be > 0 and < + 1.0, default 0.1 + --dns-private dns private key used to publish, + required, hex string of length 64 + --domain dns domain to publish nodes, required, + string + --host-zone-id if server-type is aws, it's host zone id + of aws's domain, optional, string + --known-urls known dns urls to publish, url format + tree://{pubkey}@{domain}, optional, + url[,url[...]] + --max-merge-size max merge size to merge node to a leaf + node in dns tree, optional, should be + [1~5], default 5 + -publish,--publish enable dns publish + --server-type dns server to publish, required, only + aws or aliyun is support + --static-nodes static nodes to publish, if exist then + nodes from kad will be ignored, + optional, ip:port[,ip:port[...]] +``` + +For details please +check [StartApp](src/main/java/org/tron/p2p/example/StartApp.java) +. + +## 1.1 Construct a p2p network + +For example +Node A, starts with default configuration parameters. Let's say its IP is 127.0.0.1 + +```bash +$ java -jar p2p/build/libs/p2p-standalone.jar +``` + +Node B, start with seed nodes(127.0.0.1:18888). Let's say its IP is 127.0.0.2 + +```bash +$ java -jar p2p/build/libs/p2p-standalone.jar -s 127.0.0.1:18888 +``` + +Node C, start with with seed nodes(127.0.0.1:18888). Let's say its IP is 127.0.0.3 + +```bash +$ java -jar p2p/build/libs/p2p-standalone.jar -s 127.0.0.1:18888 +``` + +After the three nodes are successfully started, the usual situation is that node B can discover node +C (or node C can discover B), and the three of them can establish a TCP connection with each other. + +## 1.2 Publish our nodes on one domain + +Libp2p support publish nodes on dns domain. Before publishing, you must enable p2p +discover. Node lists can be deployed to any DNS provider such as CloudFlare DNS, dnsimple, Amazon +Route 53, Aliyun Cloud using their respective client libraries. But we only support Amazon Route 53 +and Aliyun Cloud. +You can see more detail on https://eips.ethereum.org/EIPS/eip-1459, we implement this eip, but have +some difference in data structure. + +### 1.2.1 Acquire your apikey from Amazon Route 53 or Aliyun Cloud + +* Amazon Route 53 include: AWS Access Key ID、AWS Access Key Secret、Route53 Zone ID、AWS Region, get more info +* Aliyun Cloud include: accessKeyId、accessKeySecret、endpoint, get more info + +### 1.2.2 Publish nodes + +Suppose you have a domain example.org hosted by Amazon Route 53, you can publish your nodes automatically +like this: + +```bash +java -jar p2p/build/libs/p2p-standalone.jar -p 18888 -v 201910292 -d 1 -s 127.0.0.1:18888 \ +-publish \ +--dns-private b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291 \ +--server-type aws \ +--access-key-id \ +--access-key-secret \ +--aws-region us-east-1 \ +--host-zone-id \ +--domain nodes.example.org +``` + +This program will do following periodically: + +* get nodes from p2p discover service and construct a tree using these nodes +* collect txt records from dns domain with API +* compare tree with the txt records +* submit changes to dns domain with API if necessary. + +We can get tree's url from log: + +``` +tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@nodes.example.org +``` + +The compressed public Key APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ is responsed to +above dns-private key. + +### 1.2.3 Verify your dns txt records + +You can query dns record by following command and check if a TXT type record exists: + +```bash +dig nodes.example.org TXT +``` + +At last we can release the tree's url on anywhere later, such as github. So others can download this +tree to get nodes dynamically. + +# 2. Use as a dependency + +## 2.1 Core classes + +* [P2pService](src/main/java/org/tron/p2p/P2pService.java) + is the entry class of p2p service and provides the startup interface of p2p service and the main + interfaces provided by p2p module. +* [P2pConfig](src/main/java/org/tron/p2p/P2pConfig.java) + defines all the configurations of the p2p module, such as the listening port, the maximum number + of connections, etc. +* [P2pEventHandler](src/main/java/org/tron/p2p/P2pEventHandler.java) + is the abstract class for p2p event handler. +* [Channel](src/main/java/org/tron/p2p/connection/Channel.java) + is an implementation of the TCP connection channel in the p2p module. The new connection channel + is obtained through the `P2pEventHandler.onConnect` method. + +## 2.2 Interface + +* `P2pService.start` + - @param: p2pConfig P2pConfig + - @return: void + - desc: the startup interface of p2p service +* `P2pService.close` + - @param: + - @return: void + - desc: the close interface of p2p service +* `P2pService.register` + - @param: p2PEventHandler P2pEventHandler + - @return: void + - desc: register p2p event handler +* `P2pService.connect` + - @param: address InetSocketAddress + - @return: void + - desc: connect to a node with a socket address +* `P2pService.getAllNodes` + - @param: + - @return: List + - desc: get all the nodes +* `P2pService.getTableNodes` + - @param: + - @return: List + - desc: get all the nodes that in the hash table +* `P2pService.getConnectableNodes` + - @param: + - @return: List + - desc: get all the nodes that can be connected +* `P2pService.getP2pStats()` + - @param: + - @return: void + - desc: get statistics information of p2p service +* `Channel.send` + - @param: data byte[] + - @return: void + - desc: send messages to the peer node through the channel +* `Channel.close` + - @param: + - @return: void + - desc: the close interface of channel + +## 2.3 Steps for usage + +1. Config p2p discover parameters +2. (optional) Config dns parameters +3. Implement P2pEventHandler and register p2p event handler +4. Start p2p service +5. Use Channel's send and close interfaces as needed +6. Use P2pService's interfaces as needed + +### 2.3.1 Config discover parameters + +New p2p config instance + +```bash +P2pConfig config = new P2pConfig(); +``` + +Set p2p networkId (also called p2p version) + +```bash +config.setNetworkId(11111); +``` + +Set TCP and UDP listen port + +```bash +config.setPort(18888); +``` + +Turn node discovery on or off + +```bash +config.setDiscoverEnable(true); +``` + +Set discover seed nodes + +```bash +List seedNodeList = new ArrayList<>(); +seedNodeList.add(new InetSocketAddress("13.124.62.58", 18888)); +seedNodeList.add(new InetSocketAddress("2600:1f13:908:1b00:e1fd:5a84:251c:a32a", 18888)); +seedNodeList.add(new InetSocketAddress("[2600:1f13:908:1b00:e1fd:5a84:251c:1234]", 18888)); +seedNodeList.add(new InetSocketAddress("127.0.0.4", 18888)); +config.setSeedNodes(seedNodeList); +``` + +Set active nodes +```bash +List activeNodeList = new ArrayList<>(); +activeNodeList.add(new InetSocketAddress("127.0.0.2", 18888)); +activeNodeList.add(new InetSocketAddress("127.0.0.3", 18888)); +config.setActiveNodes(activeNodeList); +``` + +Set trust ips + +```bash +List trustNodeList = new ArrayList<>(); +trustNodeList.add((new InetSocketAddress("127.0.0.2", 18888)).getAddress()); +config.setTrustNodes(trustNodeList); +``` + +Set the minimum number of connections + +```bash +config.setMinConnections(8); +``` + +Set the minimum number of actively established connections + +```bash +config.setMinActiveConnections(2); +``` + +Set the maximum number of connections + +```bash +config.setMaxConnections(30); +``` + +Set the maximum number of connections with the same IP + +```bash +config.setMaxConnectionsWithSameIp(2); +``` + +### 2.3.2 (optional) Config dns parameters if needed +Suppose these scenes: +* you don't want to config one or many fixed seed nodes in mobile app such as wallet, because nodes may be out of service but you cannot update the app timely +* you don't known any seed node but you still want to establish tcp connection + +You can config a dns tree regardless of whether discovery service is enabled or not. Assume you have a tree url of Tron's nile or shasta or mainnet nodes that publish on github like: +```azure +tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@nodes.example.org +``` +You can config the parameters like that: +```bash +config.setDiscoverEnable(false); +String[] urls = new String[] {"tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@nodes.example.org"}; +config.setTreeUrls(Arrays.asList(urls)); +``` +After that, the module will download the nodes from nile.nftderby1.net periodically. + +### 2.3.3 TCP Handler + +Implement definition message + +```bash +public class TestMessage { + protected MessageTypes type; + protected byte[] data; + public TestMessage(byte[] data) { + this.type = MessageTypes.TEST; + this.data = data; + } + +} + +public enum MessageTypes { + + FIRST((byte)0x00), + + TEST((byte)0x01), + + LAST((byte)0x8f); + + private final byte type; + + MessageTypes(byte type) { + this.type = type; + } + + public byte getType() { + return type; + } + + private static final Map map = new HashMap<>(); + + static { + for (MessageTypes value : values()) { + map.put(value.type, value); + } + } + + public static MessageTypes fromByte(byte type) { + return map.get(type); + } + } +``` + +Inheritance implements the P2pEventHandler class. + +* `onConnect` is called back after the TCP connection is established. +* `onDisconnect` is called back after the TCP connection is closed. +* `onMessage` is called back after receiving a message on the channel. Note that `data[0]` is the + message type. + +```bash +public class MyP2pEventHandler extends P2pEventHandler { + + public MyP2pEventHandler() { + this.typeSet = new HashSet<>(); + this.typeSet.add(MessageTypes.TEST.getType()); + } + + @Override + public void onConnect(Channel channel) { + channels.put(channel.getInetSocketAddress(), channel); + } + + @Override + public void onDisconnect(Channel channel) { + channels.remove(channel.getInetSocketAddress()); + } + + @Override + public void onMessage(Channel channel, byte[] data) { + byte type = data[0]; + byte[] messageData = ArrayUtils.subarray(data, 1, data.length); + switch (MessageTypes.fromByte(type)) { + case TEST: + TestMessage message = new TestMessage(messageData); + // process TestMessage + break; + default: + // todo + } + } +} +``` + +### 2.3.4 Start p2p service + +Start p2p service with P2pConfig and P2pEventHandler + +```bash +P2pService p2pService = new P2pService(); +MyP2pEventHandler myP2pEventHandler = new MyP2pEventHandler(); +try { + p2pService.register(myP2pEventHandler); +} catch (P2pException e) { + // todo process exception +} +p2pService.start(config); +``` + +For details please +The former `ImportUsing`, `DnsExample1` and `DnsExample2` reference classes have +been replaced by +[ExampleUsageTest](src/test/java/org/tron/p2p/example/ExampleUsageTest.java), +which asserts the same configuration shapes instead of only compiling them. + + diff --git a/p2p/build.gradle b/p2p/build.gradle new file mode 100644 index 00000000000..51f27bd282e --- /dev/null +++ b/p2p/build.gradle @@ -0,0 +1,196 @@ +apply plugin: 'com.google.protobuf' +apply plugin: 'checkstyle' + +// Unit tests live in src/test/java/, alongside the code they cover. + +checkstyle { + toolVersion = "${rootProject.checkstyleVersion}" + configFile = file("${rootDir}/config/checkstyle/checkStyleAll.xml") + maxWarnings = 0 +} + +checkstyleMain { + source = 'src/main/java' + exclude '**/protos/**' +} + +checkstyleTest { + source = 'src/test/java' +} + +// The plain jar stays thin -- it is what :common depends on. Declaring +// Main-Class on it would be a trap: `java -jar p2p-1.0.0.jar` would resolve the +// entry point and then die on the first dependency it touches +// (NoClassDefFoundError: org/apache/commons/cli/ParseException). The runnable +// artifact is p2p-standalone.jar below. +// +// Same shape as :framework's FullNode.jar and :plugins' Toolkit.jar, including +// the -PbinaryRelease=false opt-out and the signature/SPI exclusions. +def releaseBinary = hasProperty('binaryRelease') ? getProperty('binaryRelease') : 'true' +if (releaseBinary == 'true') { + artifacts { + archives(tasks.create('buildStandaloneJar', Jar) { + baseName = 'p2p-standalone' + version = null + from(sourceSets.main.output) { + include '/**' + } + from { + configurations.runtimeClasspath.collect { + it.isDirectory() ? it : zipTree(it) + } + } + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + // Bouncy Castle ships signed jars; merged signatures fail verification. + exclude 'META-INF/*.SF' + exclude 'META-INF/*.DSA' + exclude 'META-INF/*.RSA' + // dnsjava's resolver SPI, see HADOOP-19288 + exclude 'META-INF/services/java.net.spi.InetAddressResolverProvider' + manifest { + attributes 'Main-Class': 'org.tron.p2p.example.StartApp' + } + }) + } +} + +// .proto files sit in src/main/proto, the protobuf plugin's default, so no +// sourceSet override is needed. The previous layout, src/main/protos with an +// explicit srcDir, builds fine but IDEA's protobuf plugin does not read the +// Gradle override -- it resolves imports against the default path -- so +// `import "Discover.proto"` and every type it brings in showed as unresolved +// in the editor. +// +// Generated sources still land in src/main/java/org/tron/p2p/protos via +// generatedFilesBaseDir below, and are gitignored. + +// These exclusions used to live on the `libp2p` dependency in common/build.gradle. +// Internalizing the module moves the same transitive dom4j tail (pulled in by the +// Aliyun/Route53 SDKs) here, so the exclusions move with it — dropping them would +// silently re-admit artifacts the project has excluded since: +// https://github.com/dom4j/dom4j/pull/116 +// https://github.com/gradle/gradle/issues/13656 +// https://github.com/dom4j/dom4j/issues/99 +configurations.configureEach { + exclude group: 'jaxen', module: 'jaxen' + exclude group: 'javax.xml.stream', module: 'stax-api' + exclude group: 'net.java.dev.msv', module: 'msv' + exclude group: 'net.java.dev.msv', module: 'xsdlib' + exclude group: 'relaxngDatatype', module: 'relaxngDatatype' + exclude group: 'pull-parser', module: 'pull-parser' + exclude group: 'xpp3', module: 'xpp3' +} + +dependencies { + // protobuf & grpc (implementation scope: not leaked to consumers) + implementation "com.google.protobuf:protobuf-java:${rootProject.protobufVersion}" + implementation "com.google.protobuf:protobuf-java-util:${rootProject.protobufVersion}" + // grpc-netty provides Netty transitively, which p2p uses for TCP/UDP transport. + // grpc itself is not used (p2p protos define only messages, no services). + // Track the project's grpc version rather than pinning libp2p's, so p2p + // cannot drift from the Netty that the rest of java-tron resolves. + implementation "io.grpc:grpc-netty:${rootProject.grpcVersion}" + // Netty 4.2 split io.netty.handler.codec.protobuf out of netty-codec into its + // own artifact, so the varint32 framing codecs p2p puts on every channel + // pipeline no longer arrive transitively. framework/build.gradle declares the + // same dependency for the same reason; both track rootProject.nettyVersion. + implementation("io.netty:netty-codec-protobuf:${rootProject.nettyVersion}") { + exclude group: 'com.google.protobuf' + exclude group: 'com.google.protobuf.nano' + } + + // p2p-specific dependencies + implementation 'org.xerial.snappy:snappy-java:1.1.10.5' + // Matches the bcprov-jdk18on version root build.gradle gives every + // subproject; bcpkix is not provided there, so declare it explicitly. + implementation 'org.bouncycastle:bcpkix-jdk18on:1.84' + implementation 'dnsjava:dnsjava:3.6.2' + implementation 'commons-cli:commons-cli:1.5.0' + implementation('software.amazon.awssdk:route53:2.18.41') { + exclude group: 'io.netty', module: 'netty-codec-http2' + exclude group: 'io.netty', module: 'netty-codec-http' + exclude group: 'io.netty', module: 'netty-common' + exclude group: 'io.netty', module: 'netty-buffer' + exclude group: 'io.netty', module: 'netty-transport' + exclude group: 'io.netty', module: 'netty-codec' + exclude group: 'io.netty', module: 'netty-handler' + exclude group: 'io.netty', module: 'netty-resolver' + exclude group: 'io.netty', module: 'netty-transport-classes-epoll' + exclude group: 'io.netty', module: 'netty-transport-native-unix-common' + exclude group: 'software.amazon.awssdk', module: 'netty-nio-client' + } + implementation('com.aliyun:alidns20150109:3.0.1') { + exclude group: 'org.bouncycastle', module: 'bcprov-jdk15on' + exclude group: 'org.bouncycastle', module: 'bcpkix-jdk15on' + exclude group: 'pull-parser', module: 'pull-parser' + exclude group: 'xpp3', module: 'xpp3' + } + + + // provided by root build.gradle for all subprojects: + // slf4j-api, logback, bcprov-jdk18on, lombok, junit, mockito +} + +protobuf { + generatedFilesBaseDir = "$projectDir/src" + protoc { + artifact = "com.google.protobuf:protoc:${rootProject.protobufVersion}" + } + generateProtoTasks { + all().each { task -> + task.builtins { + java { outputSubDir = "java" } + } + } + } +} + +clean.doFirst { + delete "src/main/java/org/tron/p2p/protos" +} + +processResources.dependsOn(generateProto) + +// The module reports its own coverage now that it has a test sourceSet. CI +// collects **/build/reports/jacoco/test/jacocoTestReport.xml across every +// module, so this is picked up without any wiring in :framework. +jacocoTestReport { + dependsOn test + reports { + xml.required = true + html.required = false + } + // Generated protobuf code, matching the checkstyle exclusion above. + // + // org/tron/p2p/example holds StartApp, the standalone CLI entry point for + // driving this module without java-tron. It is argument parsing, option + // declarations and a main() that starts services and blocks -- not module + // logic, and not code the node runs. It also sat in the checkstyle- and + // coverage-exempt `example` sourceSet until this PR, so excluding it keeps + // the measured surface the same rather than hiding newly counted logic. + // The parsing helpers it does own are covered by StartAppArgsTest. + classDirectories.setFrom(files(classDirectories.files.collect { + fileTree(dir: it, excludes: ['**/protos/**', '**/example/**']) + })) + + // :framework's own tests -- org.tron.core.net and friends -- execute a good + // deal of this module's code. That coverage is real, and while p2p's classes + // hung off :framework:jacocoTestReport it was counted. Reading framework's + // exec data here keeps counting it now that the classes live in this + // module's report instead. Without this the coverage gate sees a ~0.3 point + // drop for code that is still being exercised, just no longer measured. + // + // The fileTree is empty when :framework:test has not run, so :p2p:build on + // its own still works -- it just reports this module's tests alone. + executionData.from(fileTree("${rootProject.projectDir}/framework/build/jacoco") + .include('**/*.exec')) + mustRunAfter ':framework:test' +} + +// Prints the module's runtime classpath, so StartApp can be launched standalone +// against a thin jar. See README.md. +tasks.register('printRuntimeClasspath') { + doLast { + println sourceSets.main.runtimeClasspath.asPath + } +} diff --git a/p2p/src/main/java/org/tron/p2p/P2pConfig.java b/p2p/src/main/java/org/tron/p2p/P2pConfig.java new file mode 100644 index 00000000000..9a3aef6b9df --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/P2pConfig.java @@ -0,0 +1,37 @@ +package org.tron.p2p; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import lombok.Data; +import org.tron.p2p.dns.update.PublishConfig; +import org.tron.p2p.utils.NetUtil; + +@Data +public class P2pConfig { + + private List seedNodes = new CopyOnWriteArrayList<>(); + private List activeNodes = new CopyOnWriteArrayList<>(); + private List trustNodes = new CopyOnWriteArrayList<>(); + private byte[] nodeID = NetUtil.getNodeId(); + private String ip = NetUtil.getExternalIpV4(); + private String lanIp = NetUtil.getLanIP(); + private String ipv6 = NetUtil.getExternalIpV6(); + private int port = 18888; + private int networkId = 1; + private int minConnections = 8; + private int maxConnections = 50; + private int minActiveConnections = 2; + private int maxConnectionsWithSameIp = 2; + private boolean discoverEnable = true; + private boolean disconnectionPolicyEnable = false; + private boolean nodeDetectEnable = false; + + //dns read config + private List treeUrls = new ArrayList<>(); + + //dns publish config + private PublishConfig publishConfig = new PublishConfig(); +} diff --git a/p2p/src/main/java/org/tron/p2p/P2pEventHandler.java b/p2p/src/main/java/org/tron/p2p/P2pEventHandler.java new file mode 100644 index 00000000000..7ca3f235049 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/P2pEventHandler.java @@ -0,0 +1,20 @@ +package org.tron.p2p; + +import java.util.Set; +import lombok.Getter; +import org.tron.p2p.connection.Channel; + +public abstract class P2pEventHandler { + + @Getter + protected Set messageTypes; + + public void onConnect(Channel channel) { + } + + public void onDisconnect(Channel channel) { + } + + public void onMessage(Channel channel, byte[] data) { + } +} diff --git a/p2p/src/main/java/org/tron/p2p/P2pService.java b/p2p/src/main/java/org/tron/p2p/P2pService.java new file mode 100644 index 00000000000..5e0b05e56c8 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/P2pService.java @@ -0,0 +1,90 @@ +package org.tron.p2p; + +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.NodeManager; +import org.tron.p2p.dns.DnsManager; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.stats.P2pStats; +import org.tron.p2p.stats.StatsManager; + +@Slf4j(topic = "net") +public class P2pService { + + private StatsManager statsManager = new StatsManager(); + private volatile boolean isShutdown = false; + + public void start(P2pConfig p2pConfig) { + Parameter.p2pConfig = p2pConfig; + NodeManager.init(); + ChannelManager.init(); + DnsManager.init(); + logger.info("P2p service started"); + + Runtime.getRuntime().addShutdownHook(new Thread(this::close)); + } + + public void close() { + if (isShutdown) { + return; + } + isShutdown = true; + DnsManager.close(); + NodeManager.close(); + ChannelManager.close(); + logger.info("P2p service closed"); + } + + public void register(P2pEventHandler p2PEventHandler) throws P2pException { + Parameter.addP2pEventHandle(p2PEventHandler); + } + + @Deprecated + public void connect(InetSocketAddress address) { + ChannelManager.connect(address); + } + + public ChannelFuture connect(Node node, ChannelFutureListener future) { + return ChannelManager.connect(node, future); + } + + public P2pStats getP2pStats() { + return statsManager.getP2pStats(); + } + + public List getTableNodes() { + return NodeManager.getTableNodes(); + } + + public List getConnectableNodes() { + Set nodes = new HashSet<>(); + nodes.addAll(NodeManager.getConnectableNodes()); + nodes.addAll(DnsManager.getDnsNodes()); + return new ArrayList<>(nodes); + } + + public List getAllNodes() { + Set nodes = new HashSet<>(); + nodes.addAll(NodeManager.getAllNodes()); + nodes.addAll(DnsManager.getDnsNodes()); + return new ArrayList<>(nodes); + } + + public void updateNodeId(Channel channel, String nodeId) { + ChannelManager.updateNodeId(channel, nodeId); + } + + public int getVersion() { + return Parameter.version; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/base/Constant.java b/p2p/src/main/java/org/tron/p2p/base/Constant.java new file mode 100644 index 00000000000..b87cfa287f5 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/base/Constant.java @@ -0,0 +1,16 @@ +package org.tron.p2p.base; + +import java.util.Arrays; +import java.util.List; + +public class Constant { + + public static final int NODE_ID_LEN = 64; + public static final List ipV4Urls = Arrays.asList( + "http://checkip.amazonaws.com", "https://ifconfig.me/ip", "https://4.ipw.cn/"); + public static final List ipV6Urls = Arrays.asList( + "https://v6.ident.me", "http://6.ipw.cn/", "https://api6.ipify.org", + "https://ipv6.icanhazip.com"); + public static final String ipV4Hex = "00000000"; //32 bit + public static final String ipV6Hex = "00000000000000000000000000000000"; //128 bit +} diff --git a/p2p/src/main/java/org/tron/p2p/base/Parameter.java b/p2p/src/main/java/org/tron/p2p/base/Parameter.java new file mode 100644 index 00000000000..a53f74b9a33 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/base/Parameter.java @@ -0,0 +1,74 @@ +package org.tron.p2p.base; + +import com.google.protobuf.ByteString; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import lombok.Data; +import org.apache.commons.lang3.StringUtils; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.P2pEventHandler; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.exception.P2pException.TypeEnum; +import org.tron.p2p.protos.Discover; +import org.tron.p2p.utils.ByteArray; + +@Data +public class Parameter { + + public static int version = 1; + + public static final int TCP_NETTY_WORK_THREAD_NUM = 0; + + public static final int UDP_NETTY_WORK_THREAD_NUM = 1; + + public static final int CONN_MAX_QUEUE_SIZE = 10; + + public static final int NODE_CONNECTION_TIMEOUT = 2000; + + public static final int KEEP_ALIVE_TIMEOUT = 20_000; + + public static final int PING_TIMEOUT = 20_000; + + public static final int NETWORK_TIME_DIFF = 1000; + + public static final long DEFAULT_BAN_TIME = 60_000; + + public static final int MAX_MESSAGE_LENGTH = 5 * 1024 * 1024; + + public static volatile P2pConfig p2pConfig; + + public static volatile List handlerList = new ArrayList<>(); + + public static volatile Map handlerMap = new HashMap<>(); + + public static void addP2pEventHandle(P2pEventHandler p2PEventHandler) throws P2pException { + if (p2PEventHandler.getMessageTypes() != null) { + for (Byte type : p2PEventHandler.getMessageTypes()) { + if (handlerMap.get(type) != null) { + throw new P2pException(TypeEnum.TYPE_ALREADY_REGISTERED, "type:" + type); + } + } + for (Byte type : p2PEventHandler.getMessageTypes()) { + handlerMap.put(type, p2PEventHandler); + } + } + handlerList.add(p2PEventHandler); + } + + public static Discover.Endpoint getHomeNode() { + Discover.Endpoint.Builder builder = Discover.Endpoint.newBuilder() + .setNodeId(ByteString.copyFrom(Parameter.p2pConfig.getNodeID())) + .setPort(Parameter.p2pConfig.getPort()); + if (StringUtils.isNotEmpty(Parameter.p2pConfig.getIp())) { + builder.setAddress(ByteString.copyFrom( + ByteArray.fromString(Parameter.p2pConfig.getIp()))); + } + if (StringUtils.isNotEmpty(Parameter.p2pConfig.getIpv6())) { + builder.setAddressIpv6(ByteString.copyFrom( + ByteArray.fromString(Parameter.p2pConfig.getIpv6()))); + } + return builder.build(); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/Channel.java b/p2p/src/main/java/org/tron/p2p/connection/Channel.java new file mode 100644 index 00000000000..811904b7d27 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/Channel.java @@ -0,0 +1,204 @@ +package org.tron.p2p.connection; + +import com.google.common.base.Throwables; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPipeline; +import io.netty.handler.codec.CorruptedFrameException; +import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; +import io.netty.handler.timeout.ReadTimeoutException; +import io.netty.handler.timeout.ReadTimeoutHandler; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.business.upgrade.UpgradeController; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.handshake.HelloMessage; +import org.tron.p2p.connection.socket.MessageHandler; +import org.tron.p2p.connection.socket.P2pProtobufVarint32FrameDecoder; +import org.tron.p2p.discover.Node; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.stats.TrafficStats; +import org.tron.p2p.utils.ByteArray; + +@Slf4j(topic = "net") +public class Channel { + + public volatile boolean waitForPong = false; + public volatile long pingSent = System.currentTimeMillis(); + + @Getter + private HelloMessage helloMessage; + @Getter + private Node node; + @Getter + private int version; + @Getter + private ChannelHandlerContext ctx; + @Getter + private InetSocketAddress inetSocketAddress; + @Getter + private InetAddress inetAddress; + @Getter + private volatile long disconnectTime; + @Getter + @Setter + private volatile boolean isDisconnect = false; + @Getter + @Setter + private long lastSendTime = System.currentTimeMillis(); + @Getter + private final long startTime = System.currentTimeMillis(); + @Getter + private boolean isActive = false; + @Getter + private boolean isTrustPeer; + @Getter + @Setter + private volatile boolean finishHandshake; + @Getter + @Setter + private String nodeId; + @Setter + @Getter + private boolean discoveryMode; + @Getter + private long avgLatency; + private long count; + + public void init(ChannelPipeline pipeline, String nodeId, boolean discoveryMode) { + this.discoveryMode = discoveryMode; + this.nodeId = nodeId; + this.isActive = StringUtils.isNotEmpty(nodeId); + MessageHandler messageHandler = new MessageHandler(this); + pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60, TimeUnit.SECONDS)); + pipeline.addLast(TrafficStats.tcp); + pipeline.addLast("protoPrepend", new ProtobufVarint32LengthFieldPrepender()); + pipeline.addLast("protoDecode", new P2pProtobufVarint32FrameDecoder(this)); + pipeline.addLast("messageHandler", messageHandler); + } + + public void processException(Throwable throwable) { + Throwable baseThrowable = throwable; + try { + baseThrowable = Throwables.getRootCause(baseThrowable); + } catch (IllegalArgumentException e) { + baseThrowable = e.getCause(); + logger.warn("Loop in causal chain detected"); + } + SocketAddress address = ctx.channel().remoteAddress(); + if (throwable instanceof ReadTimeoutException + || throwable instanceof IOException + || throwable instanceof CorruptedFrameException) { + logger.warn("Close peer {}, reason: {}", address, throwable.getMessage()); + } else if (baseThrowable instanceof P2pException) { + logger.warn("Close peer {}, type: ({}), info: {}", + address, ((P2pException) baseThrowable).getType(), baseThrowable.getMessage()); + } else { + logger.error("Close peer {}, exception caught", address, throwable); + } + close(); + } + + public void setHelloMessage(HelloMessage helloMessage) { + this.helloMessage = helloMessage; + this.node = helloMessage.getFrom(); + this.nodeId = node.getHexId(); //update node id from handshake + this.version = helloMessage.getVersion(); + } + + public void setChannelHandlerContext(ChannelHandlerContext ctx) { + this.ctx = ctx; + this.inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress(); + this.inetAddress = inetSocketAddress.getAddress(); + this.isTrustPeer = Parameter.p2pConfig.getTrustNodes().contains(inetAddress); + } + + public void close(long banTime) { + this.isDisconnect = true; + this.disconnectTime = System.currentTimeMillis(); + ChannelManager.banNode(this.inetAddress, banTime); + ctx.close(); + } + + public void close() { + close(Parameter.DEFAULT_BAN_TIME); + } + + public void send(Message message) { + if (message.needToLog()) { + logger.info("Send message to channel {}, {}", inetSocketAddress, message); + } else { + logger.debug("Send message to channel {}, {}", inetSocketAddress, message); + } + send(message.getSendData()); + } + + public void send(byte[] data) { + try { + byte type = data[0]; + if (isDisconnect) { + logger.warn("Send to {} failed as channel has closed, message-type:{} ", + ctx.channel().remoteAddress(), type); + return; + } + + if (finishHandshake) { + data = UpgradeController.codeSendData(version, data); + } + + ByteBuf byteBuf = Unpooled.wrappedBuffer(data); + ctx.writeAndFlush(byteBuf).addListener((ChannelFutureListener) future -> { + if (!future.isSuccess() && !isDisconnect) { + logger.warn("Send to {} failed, message-type:{}, cause:{}", + ctx.channel().remoteAddress(), ByteArray.byte2int(type), + future.cause().getMessage()); + } + }); + setLastSendTime(System.currentTimeMillis()); + } catch (Exception e) { + logger.warn("Send message to {} failed, {}", inetSocketAddress, e.getMessage()); + ctx.channel().close(); + } + } + + public void updateAvgLatency(long latency) { + long total = this.avgLatency * this.count; + this.count++; + this.avgLatency = (total + latency) / this.count; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Channel channel = (Channel) o; + return Objects.equals(inetSocketAddress, channel.inetSocketAddress); + } + + @Override + public int hashCode() { + return inetSocketAddress.hashCode(); + } + + @Override + public String toString() { + return String.format("%s | %s", inetSocketAddress, + StringUtils.isEmpty(nodeId) ? "" : nodeId); + } + +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/ChannelManager.java b/p2p/src/main/java/org/tron/p2p/connection/ChannelManager.java new file mode 100644 index 00000000000..d32fe2f1a3a --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/ChannelManager.java @@ -0,0 +1,307 @@ +package org.tron.p2p.connection; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.bouncycastle.util.encoders.Hex; +import org.tron.p2p.P2pEventHandler; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.business.detect.NodeDetectService; +import org.tron.p2p.connection.business.handshake.DisconnectCode; +import org.tron.p2p.connection.business.handshake.HandshakeService; +import org.tron.p2p.connection.business.keepalive.KeepAliveService; +import org.tron.p2p.connection.business.pool.ConnPoolService; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.connection.message.base.P2pDisconnectMessage; +import org.tron.p2p.connection.socket.PeerClient; +import org.tron.p2p.connection.socket.PeerServer; +import org.tron.p2p.discover.Node; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.exception.P2pException.TypeEnum; +import org.tron.p2p.protos.Connect.DisconnectReason; +import org.tron.p2p.utils.ByteArray; +import org.tron.p2p.utils.NetUtil; + +@Slf4j(topic = "net") +public class ChannelManager { + + @Getter + private static NodeDetectService nodeDetectService; + + private static PeerServer peerServer; + + @Getter + private static PeerClient peerClient; + + @Getter + private static ConnPoolService connPoolService; + + private static KeepAliveService keepAliveService; + + @Getter + private static HandshakeService handshakeService; + + @Getter + private static final Map channels = new ConcurrentHashMap<>(); + + @Getter + private static final Cache bannedNodes = CacheBuilder + .newBuilder().maximumSize(2000).build(); //ban timestamp + + private static boolean isInit = false; + public static volatile boolean isShutdown = false; + + public static void init() { + isInit = true; + peerServer = new PeerServer(); + peerClient = new PeerClient(); + keepAliveService = new KeepAliveService(); + connPoolService = new ConnPoolService(); + handshakeService = new HandshakeService(); + nodeDetectService = new NodeDetectService(); + peerServer.init(); + peerClient.init(); + keepAliveService.init(); + connPoolService.init(peerClient); + nodeDetectService.init(peerClient); + } + + public static void connect(InetSocketAddress address) { + peerClient.connect(address.getAddress().getHostAddress(), address.getPort(), + ByteArray.toHexString(NetUtil.getNodeId())); + } + + public static ChannelFuture connect(Node node, ChannelFutureListener future) { + return peerClient.connect(node, future); + } + + public static void notifyDisconnect(Channel channel) { + if (channel.getInetSocketAddress() == null) { + logger.warn("Notify Disconnect peer has no address."); + return; + } + channels.remove(channel.getInetSocketAddress()); + Parameter.handlerList.forEach(h -> h.onDisconnect(channel)); + InetAddress inetAddress = channel.getInetAddress(); + if (inetAddress != null) { + banNode(inetAddress, Parameter.DEFAULT_BAN_TIME); + } + } + + public static int getConnectionNum(InetAddress inetAddress) { + int cnt = 0; + for (Channel channel : channels.values()) { + if (channel.getInetAddress().equals(inetAddress)) { + cnt++; + } + } + return cnt; + } + + public static synchronized DisconnectCode processPeer(Channel channel) { + + if (!channel.isActive() && !channel.isTrustPeer()) { + InetAddress inetAddress = channel.getInetAddress(); + if (bannedNodes.getIfPresent(inetAddress) != null + && bannedNodes.getIfPresent(inetAddress) > System.currentTimeMillis()) { + logger.info("Peer {} recently disconnected", channel); + return DisconnectCode.TIME_BANNED; + } + + if (channels.size() >= Parameter.p2pConfig.getMaxConnections()) { + logger.info("Too many peers, disconnected with {}", channel); + return DisconnectCode.TOO_MANY_PEERS; + } + + int num = getConnectionNum(channel.getInetAddress()); + if (num >= Parameter.p2pConfig.getMaxConnectionsWithSameIp()) { + logger.info("Max connection with same ip {}", channel); + return DisconnectCode.MAX_CONNECTION_WITH_SAME_IP; + } + } + + if (StringUtils.isNotEmpty(channel.getNodeId())) { + for (Channel c : channels.values()) { + if (channel.getNodeId().equals(c.getNodeId())) { + if (c.getStartTime() > channel.getStartTime()) { + c.close(); + } else { + logger.info("Duplicate peer {}, exist peer {}", channel, c); + return DisconnectCode.DUPLICATE_PEER; + } + } + } + } + + channels.put(channel.getInetSocketAddress(), channel); + + logger.info("Add peer {}, total channels: {}", channel.getInetSocketAddress(), channels.size()); + return DisconnectCode.NORMAL; + } + + public static DisconnectReason getDisconnectReason(DisconnectCode code) { + DisconnectReason disconnectReason; + switch (code) { + case DIFFERENT_VERSION: + disconnectReason = DisconnectReason.DIFFERENT_VERSION; + break; + case TIME_BANNED: + disconnectReason = DisconnectReason.RECENT_DISCONNECT; + break; + case DUPLICATE_PEER: + disconnectReason = DisconnectReason.DUPLICATE_PEER; + break; + case TOO_MANY_PEERS: + disconnectReason = DisconnectReason.TOO_MANY_PEERS; + break; + case MAX_CONNECTION_WITH_SAME_IP: + disconnectReason = DisconnectReason.TOO_MANY_PEERS_WITH_SAME_IP; + break; + default: { + disconnectReason = DisconnectReason.UNKNOWN; + } + } + return disconnectReason; + } + + public static void logDisconnectReason(Channel channel, DisconnectReason reason) { + logger.info("Try to close channel: {}, reason: {}", channel.getInetSocketAddress(), + reason.name()); + } + + public static void banNode(InetAddress inetAddress, Long banTime) { + long now = System.currentTimeMillis(); + if (bannedNodes.getIfPresent(inetAddress) == null + || bannedNodes.getIfPresent(inetAddress) < now) { + bannedNodes.put(inetAddress, now + banTime); + } + } + + public static void close() { + if (!isInit || isShutdown) { + return; + } + isShutdown = true; + connPoolService.close(); + keepAliveService.close(); + peerServer.close(); + peerClient.close(); + nodeDetectService.close(); + } + + + public static void processMessage(Channel channel, byte[] data) throws P2pException { + if (data == null || data.length == 0) { + throw new P2pException(TypeEnum.EMPTY_MESSAGE, ""); + } + if (data[0] >= 0) { + handMessage(channel, data); + return; + } + + Message message = Message.parse(data); + + if (message.needToLog()) { + logger.info("Receive message from channel: {}, {}", channel.getInetSocketAddress(), message); + } else { + logger.debug("Receive message from channel {}, {}", channel.getInetSocketAddress(), message); + } + + if (channel.isDiscoveryMode() && message.getType() != MessageType.STATUS) { + logger.debug("Discovery channel {} received unexpected message {}, close it", + channel.getInetSocketAddress(), message.getType()); + channel.close(); + return; + } + + switch (message.getType()) { + case KEEP_ALIVE_PING: + case KEEP_ALIVE_PONG: + keepAliveService.processMessage(channel, message); + break; + case HANDSHAKE_HELLO: + handshakeService.processMessage(channel, message); + break; + case STATUS: + nodeDetectService.processMessage(channel, message); + break; + case DISCONNECT: + channel.close(); + break; + default: + throw new P2pException(P2pException.TypeEnum.NO_SUCH_MESSAGE, "type:" + data[0]); + } + } + + private static void handMessage(Channel channel, byte[] data) throws P2pException { + P2pEventHandler handler = Parameter.handlerMap.get(data[0]); + if (handler == null) { + throw new P2pException(P2pException.TypeEnum.NO_SUCH_MESSAGE, "type:" + data[0]); + } + if (channel.isDiscoveryMode()) { + channel.send(new P2pDisconnectMessage(DisconnectReason.DISCOVER_MODE)); + channel.getCtx().close(); + return; + } + + if (!channel.isFinishHandshake()) { + channel.setFinishHandshake(true); + DisconnectCode code = processPeer(channel); + if (!DisconnectCode.NORMAL.equals(code)) { + DisconnectReason disconnectReason = getDisconnectReason(code); + channel.send(new P2pDisconnectMessage(disconnectReason)); + channel.getCtx().close(); + return; + } + Parameter.handlerList.forEach(h -> h.onConnect(channel)); + } + + handler.onMessage(channel, data); + } + + public static synchronized void updateNodeId(Channel channel, String nodeId) { + channel.setNodeId(nodeId); + if (nodeId.equals(Hex.toHexString(Parameter.p2pConfig.getNodeID()))) { + logger.warn("Channel {} is myself", channel.getInetSocketAddress()); + channel.send(new P2pDisconnectMessage(DisconnectReason.DUPLICATE_PEER)); + channel.close(); + return; + } + + List list = new ArrayList<>(); + channels.values().forEach(c -> { + if (nodeId.equals(c.getNodeId())) { + list.add(c); + } + }); + if (list.size() <= 1) { + return; + } + Channel c1 = list.get(0); + Channel c2 = list.get(1); + if (c1.getStartTime() > c2.getStartTime()) { + logger.info("Close channel {}, other channel {} is earlier", c1, c2); + c1.send(new P2pDisconnectMessage(DisconnectReason.DUPLICATE_PEER)); + c1.close(); + } else { + logger.info("Close channel {}, other channel {} is earlier", c2, c1); + c2.send(new P2pDisconnectMessage(DisconnectReason.DUPLICATE_PEER)); + c2.close(); + } + } + + public static void triggerConnect(InetSocketAddress address) { + connPoolService.triggerConnect(address); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/business/MessageProcess.java b/p2p/src/main/java/org/tron/p2p/connection/business/MessageProcess.java new file mode 100644 index 00000000000..cf731e23398 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/business/MessageProcess.java @@ -0,0 +1,8 @@ +package org.tron.p2p.connection.business; + +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.message.Message; + +public interface MessageProcess { + void processMessage(Channel channel, Message message); +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/business/detect/NodeDetectService.java b/p2p/src/main/java/org/tron/p2p/connection/business/detect/NodeDetectService.java new file mode 100644 index 00000000000..0498cb38bdd --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/business/detect/NodeDetectService.java @@ -0,0 +1,229 @@ +package org.tron.p2p.connection.business.detect; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.business.MessageProcess; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.detect.StatusMessage; +import org.tron.p2p.connection.socket.PeerClient; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.NodeManager; + +@Slf4j(topic = "net") +public class NodeDetectService implements MessageProcess { + + private PeerClient peerClient; + + private Map nodeStatMap = new ConcurrentHashMap<>(); + + @Getter + private static final Cache badNodesCache = CacheBuilder + .newBuilder().maximumSize(5000).expireAfterWrite(1, TimeUnit.HOURS).build(); + + private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor( + BasicThreadFactory.builder().namingPattern("nodeDetectService").build()); + + private final long NODE_DETECT_THRESHOLD = 5 * 60 * 1000; + + private final long NODE_DETECT_MIN_THRESHOLD = 30 * 1000; + + private final long NODE_DETECT_TIMEOUT = 2 * 1000; + + private final int MAX_NODE_SLOW_DETECT = 3; + + private final int MAX_NODE_NORMAL_DETECT = 10; + + private final int MAX_NODE_FAST_DETECT = 100; + + private final int MAX_NODES = 300; + + private final int MIN_NODES = 200; + + + public void init(PeerClient peerClient) { + if (!Parameter.p2pConfig.isNodeDetectEnable()) { + return; + } + this.peerClient = peerClient; + executor.scheduleWithFixedDelay(() -> { + try { + work(); + } catch (Exception t) { + logger.warn("Exception in node detect worker, {}", t.getMessage()); + } + }, 1, 5, TimeUnit.SECONDS); + } + + public void close() { + executor.shutdown(); + } + + public void work() { + trimNodeMap(); + if (nodeStatMap.size() < MIN_NODES) { + loadNodes(); + } + + List nodeStats = getSortedNodeStats(); + if (nodeStats.size() == 0) { + return; + } + + NodeStat nodeStat = nodeStats.get(0); + if (nodeStat.getLastDetectTime() > System.currentTimeMillis() - NODE_DETECT_MIN_THRESHOLD) { + return; + } + + int n = MAX_NODE_NORMAL_DETECT; + if (nodeStat.getLastDetectTime() > System.currentTimeMillis() - NODE_DETECT_THRESHOLD) { + n = MAX_NODE_SLOW_DETECT; + } + + n = StrictMath.min(n, nodeStats.size()); + + for (int i = 0; i < n; i++) { + detect(nodeStats.get(i)); + } + } + + public void trimNodeMap() { + long now = System.currentTimeMillis(); + nodeStatMap.forEach((k, v) -> { + if (!v.finishDetect() && v.getLastDetectTime() < now - NODE_DETECT_TIMEOUT) { + nodeStatMap.remove(k); + badNodesCache.put(k.getAddress(), System.currentTimeMillis()); + } + }); + } + + private void loadNodes() { + int size = nodeStatMap.size(); + int count = 0; + List nodes = NodeManager.getConnectableNodes(); + for (Node node : nodes) { + InetSocketAddress socketAddress = node.getPreferInetSocketAddress(); + if (socketAddress != null + && !nodeStatMap.containsKey(socketAddress) + && badNodesCache.getIfPresent(socketAddress.getAddress()) == null) { + NodeStat nodeStat = new NodeStat(node); + nodeStatMap.put(socketAddress, nodeStat); + detect(nodeStat); + count++; + if (count >= MAX_NODE_FAST_DETECT || count + size >= MAX_NODES) { + break; + } + } + } + } + + private void detect(NodeStat stat) { + try { + stat.setTotalCount(stat.getTotalCount() + 1); + setLastDetectTime(stat); + peerClient.connectAsync(stat.getNode(), true); + } catch (Exception e) { + logger.warn("Detect node {} failed, {}", + stat.getNode().getPreferInetSocketAddress(), e.getMessage()); + nodeStatMap.remove(stat.getSocketAddress()); + } + } + + public synchronized void processMessage(Channel channel, Message message) { + StatusMessage statusMessage = (StatusMessage) message; + + if (!channel.isActive()) { + channel.setDiscoveryMode(true); + channel.send(new StatusMessage()); + channel.getCtx().close(); + return; + } + + InetSocketAddress socketAddress = channel.getInetSocketAddress(); + NodeStat nodeStat = nodeStatMap.get(socketAddress); + if (nodeStat == null) { + return; + } + + long cost = System.currentTimeMillis() - nodeStat.getLastDetectTime(); + if (cost > NODE_DETECT_TIMEOUT + || statusMessage.getRemainConnections() == 0) { + badNodesCache.put(socketAddress.getAddress(), cost); + nodeStatMap.remove(socketAddress); + } + + nodeStat.setLastSuccessDetectTime(nodeStat.getLastDetectTime()); + setStatusMessage(nodeStat, statusMessage); + + channel.getCtx().close(); + } + + public void notifyDisconnect(Channel channel) { + + if (!channel.isActive()) { + return; + } + + InetSocketAddress socketAddress = channel.getInetSocketAddress(); + if (socketAddress == null) { + return; + } + + NodeStat nodeStat = nodeStatMap.get(socketAddress); + if (nodeStat == null) { + return; + } + + if (nodeStat.getLastDetectTime() != nodeStat.getLastSuccessDetectTime()) { + badNodesCache.put(socketAddress.getAddress(), System.currentTimeMillis()); + nodeStatMap.remove(socketAddress); + } + } + + private synchronized List getSortedNodeStats() { + List nodeStats = new ArrayList<>(nodeStatMap.values()); + nodeStats.sort(Comparator.comparingLong(o -> o.getLastDetectTime())); + return nodeStats; + } + + private synchronized void setLastDetectTime(NodeStat nodeStat) { + nodeStat.setLastDetectTime(System.currentTimeMillis()); + } + + private synchronized void setStatusMessage(NodeStat nodeStat, StatusMessage message) { + nodeStat.setStatusMessage(message); + } + + public synchronized List getConnectableNodes() { + List stats = new ArrayList<>(); + List nodes = new ArrayList<>(); + nodeStatMap.values().forEach(stat -> { + if (stat.getStatusMessage() != null) { + stats.add(stat); + } + }); + + if (stats.isEmpty()) { + return nodes; + } + + stats.sort(Comparator.comparingInt(o -> -o.getStatusMessage().getRemainConnections())); + stats.forEach(stat -> nodes.add(stat.getNode())); + return nodes; + } + +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/business/detect/NodeStat.java b/p2p/src/main/java/org/tron/p2p/connection/business/detect/NodeStat.java new file mode 100644 index 00000000000..395df70e314 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/business/detect/NodeStat.java @@ -0,0 +1,25 @@ +package org.tron.p2p.connection.business.detect; + +import java.net.InetSocketAddress; +import lombok.Data; +import org.tron.p2p.connection.message.detect.StatusMessage; +import org.tron.p2p.discover.Node; + +@Data +public class NodeStat { + private int totalCount; + private long lastDetectTime; + private long lastSuccessDetectTime; + private StatusMessage statusMessage; + private Node node; + private InetSocketAddress socketAddress; + + public NodeStat(Node node) { + this.node = node; + this.socketAddress = node.getPreferInetSocketAddress(); + } + + public boolean finishDetect() { + return this.lastDetectTime == this.lastSuccessDetectTime; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/business/handshake/DisconnectCode.java b/p2p/src/main/java/org/tron/p2p/connection/business/handshake/DisconnectCode.java new file mode 100644 index 00000000000..fc4c9224988 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/business/handshake/DisconnectCode.java @@ -0,0 +1,30 @@ +package org.tron.p2p.connection.business.handshake; + +public enum DisconnectCode { + NORMAL(0), + TOO_MANY_PEERS(1), + DIFFERENT_VERSION(2), + TIME_BANNED(3), + DUPLICATE_PEER(4), + MAX_CONNECTION_WITH_SAME_IP(5), + UNKNOWN(256); + + private final Integer value; + + DisconnectCode(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + public static DisconnectCode forNumber(int code) { + for (DisconnectCode disconnectCode : values()) { + if (disconnectCode.value == code) { + return disconnectCode; + } + } + return UNKNOWN; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/business/handshake/HandshakeService.java b/p2p/src/main/java/org/tron/p2p/connection/business/handshake/HandshakeService.java new file mode 100644 index 00000000000..38ba25c22ed --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/business/handshake/HandshakeService.java @@ -0,0 +1,90 @@ +package org.tron.p2p.connection.business.handshake; + +import static org.tron.p2p.connection.ChannelManager.getDisconnectReason; +import static org.tron.p2p.connection.ChannelManager.logDisconnectReason; + +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.connection.business.MessageProcess; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.base.P2pDisconnectMessage; +import org.tron.p2p.connection.message.handshake.HelloMessage; +import org.tron.p2p.protos.Connect.DisconnectReason; + +@Slf4j(topic = "net") +public class HandshakeService implements MessageProcess { + + private final int networkId = Parameter.p2pConfig.getNetworkId(); + + public void startHandshake(Channel channel) { + sendHelloMsg(channel, DisconnectCode.NORMAL, channel.getStartTime()); + } + + @Override + public void processMessage(Channel channel, Message message) { + HelloMessage msg = (HelloMessage) message; + + if (channel.isFinishHandshake()) { + logger.warn("Close channel {}, handshake is finished", channel.getInetSocketAddress()); + channel.send(new P2pDisconnectMessage(DisconnectReason.DUP_HANDSHAKE)); + channel.close(); + return; + } + + channel.setHelloMessage(msg); + + DisconnectCode code = ChannelManager.processPeer(channel); + if (code != DisconnectCode.NORMAL) { + if (!channel.isActive()) { + sendHelloMsg(channel, code, msg.getTimestamp()); + } + logDisconnectReason(channel, getDisconnectReason(code)); + channel.close(); + return; + } + + ChannelManager.updateNodeId(channel, msg.getFrom().getHexId()); + if (channel.isDisconnect()) { + return; + } + + if (channel.isActive()) { + if (msg.getCode() != DisconnectCode.NORMAL.getValue() + || (msg.getNetworkId() != networkId && msg.getVersion() != networkId)) { + DisconnectCode disconnectCode = DisconnectCode.forNumber(msg.getCode()); + //v0.1 have version, v0.2 both have version and networkId + logger.info("Handshake failed {}, code: {}, reason: {}, networkId: {}, version: {}", + channel.getInetSocketAddress(), + msg.getCode(), + disconnectCode.name(), + msg.getNetworkId(), + msg.getVersion()); + logDisconnectReason(channel, getDisconnectReason(disconnectCode)); + channel.close(); + return; + } + } else { + + if (msg.getNetworkId() != networkId) { + logger.info("Peer {} different network id, peer->{}, me->{}", + channel.getInetSocketAddress(), msg.getNetworkId(), networkId); + sendHelloMsg(channel, DisconnectCode.DIFFERENT_VERSION, msg.getTimestamp()); + logDisconnectReason(channel, DisconnectReason.DIFFERENT_VERSION); + channel.close(); + return; + } + sendHelloMsg(channel, DisconnectCode.NORMAL, msg.getTimestamp()); + } + channel.setFinishHandshake(true); + channel.updateAvgLatency(System.currentTimeMillis() - channel.getStartTime()); + Parameter.handlerList.forEach(h -> h.onConnect(channel)); + } + + private void sendHelloMsg(Channel channel, DisconnectCode code, long time) { + HelloMessage helloMessage = new HelloMessage(code, time); + channel.send(helloMessage); + } + +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/business/keepalive/KeepAliveService.java b/p2p/src/main/java/org/tron/p2p/connection/business/keepalive/KeepAliveService.java new file mode 100644 index 00000000000..2b7a3e5ef91 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/business/keepalive/KeepAliveService.java @@ -0,0 +1,70 @@ +package org.tron.p2p.connection.business.keepalive; + +import static org.tron.p2p.base.Parameter.KEEP_ALIVE_TIMEOUT; +import static org.tron.p2p.base.Parameter.PING_TIMEOUT; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.connection.business.MessageProcess; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.base.P2pDisconnectMessage; +import org.tron.p2p.connection.message.keepalive.PingMessage; +import org.tron.p2p.connection.message.keepalive.PongMessage; +import org.tron.p2p.protos.Connect.DisconnectReason; + +@Slf4j(topic = "net") +public class KeepAliveService implements MessageProcess { + + private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor( + BasicThreadFactory.builder().namingPattern("keepAlive").build()); + + public void init() { + executor.scheduleWithFixedDelay(() -> { + try { + long now = System.currentTimeMillis(); + ChannelManager.getChannels().values().stream() + .filter(p -> !p.isDisconnect()) + .forEach(p -> { + if (p.waitForPong) { + if (now - p.pingSent > KEEP_ALIVE_TIMEOUT) { + p.send(new P2pDisconnectMessage(DisconnectReason.PING_TIMEOUT)); + p.close(); + } + } else { + if (now - p.getLastSendTime() > PING_TIMEOUT && p.isFinishHandshake()) { + p.send(new PingMessage()); + p.waitForPong = true; + p.pingSent = now; + } + } + }); + } catch (Exception t) { + logger.error("Exception in keep alive task", t); + } + }, 2, 2, TimeUnit.SECONDS); + } + + public void close() { + executor.shutdown(); + } + + @Override + public void processMessage(Channel channel, Message message) { + switch (message.getType()) { + case KEEP_ALIVE_PING: + channel.send(new PongMessage()); + break; + case KEEP_ALIVE_PONG: + channel.updateAvgLatency(System.currentTimeMillis() - channel.pingSent); + channel.waitForPong = false; + break; + default: + break; + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/business/pool/ConnPoolService.java b/p2p/src/main/java/org/tron/p2p/connection/business/pool/ConnPoolService.java new file mode 100644 index 00000000000..a7a4ddf2710 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/business/pool/ConnPoolService.java @@ -0,0 +1,346 @@ +package org.tron.p2p.connection.business.pool; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.bouncycastle.util.encoders.Hex; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.P2pEventHandler; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.connection.message.base.P2pDisconnectMessage; +import org.tron.p2p.connection.socket.PeerClient; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.NodeManager; +import org.tron.p2p.dns.DnsManager; +import org.tron.p2p.dns.DnsNode; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.protos.Connect.DisconnectReason; +import org.tron.p2p.utils.CollectionUtils; +import org.tron.p2p.utils.NetUtil; + +@Slf4j(topic = "net") +public class ConnPoolService extends P2pEventHandler { + + private final List activePeers = Collections.synchronizedList(new ArrayList<>()); + private final Cache peerClientCache = CacheBuilder.newBuilder() + .maximumSize(1000).expireAfterWrite(120, TimeUnit.SECONDS).recordStats().build(); + @Getter + private final AtomicInteger passivePeersCount = new AtomicInteger(0); + @Getter + private final AtomicInteger activePeersCount = new AtomicInteger(0); + @Getter + private final AtomicInteger connectingPeersCount = new AtomicInteger(0); + private final ScheduledThreadPoolExecutor poolLoopExecutor = new ScheduledThreadPoolExecutor(1, + BasicThreadFactory.builder().namingPattern("connPool").build()); + private final ScheduledExecutorService disconnectExecutor = + Executors.newSingleThreadScheduledExecutor( + BasicThreadFactory.builder().namingPattern("randomDisconnect").build()); + + public P2pConfig p2pConfig = Parameter.p2pConfig; + private PeerClient peerClient; + private final List configActiveNodes = new ArrayList<>(); + private int minCandidateSize = 50; + + public ConnPoolService() { + this.messageTypes = new HashSet<>(); //no message type registers + try { + Parameter.addP2pEventHandle(this); + configActiveNodes.addAll(p2pConfig.getActiveNodes()); + } catch (P2pException e) { + //no exception will throw + } + } + + public void init(PeerClient peerClient) { + this.peerClient = peerClient; + poolLoopExecutor.scheduleWithFixedDelay(() -> { + try { + connect(false); + } catch (Exception t) { + logger.error("Exception in poolLoopExecutor worker", t); + } + }, 200, 3600, TimeUnit.MILLISECONDS); + + if (p2pConfig.isDisconnectionPolicyEnable()) { + disconnectExecutor.scheduleWithFixedDelay(() -> { + try { + check(); + } catch (Exception t) { + logger.error("Exception in disconnectExecutor worker", t); + } + }, 30, 30, TimeUnit.SECONDS); + } + } + + private void addNode(Set inetSet, Node node) { + if (node != null) { + if (node.getInetSocketAddressV4() != null) { + inetSet.add(node.getInetSocketAddressV4()); + } + if (node.getInetSocketAddressV6() != null) { + inetSet.add(node.getInetSocketAddressV6()); + } + } + } + + private void connect(boolean isFilterActiveNodes) { + List connectNodes = new ArrayList<>(); + + //collect already used nodes in channelManager + Set addressInUse = new HashSet<>(); + Set inetInUse = new HashSet<>(); + Set nodesInUse = new HashSet<>(); + nodesInUse.add(Hex.toHexString(p2pConfig.getNodeID())); + ChannelManager.getChannels().values().forEach(channel -> { + if (StringUtils.isNotEmpty(channel.getNodeId())) { + nodesInUse.add(channel.getNodeId()); + } + addressInUse.add(channel.getInetAddress()); + inetInUse.add(channel.getInetSocketAddress()); + addNode(inetInUse, channel.getNode()); + }); + + addNode(inetInUse, new Node(Parameter.p2pConfig.getNodeID(), Parameter.p2pConfig.getIp(), + Parameter.p2pConfig.getIpv6(), Parameter.p2pConfig.getPort())); + + p2pConfig.getActiveNodes().forEach(address -> { + if (!isFilterActiveNodes && !inetInUse.contains(address) && !addressInUse.contains( + address.getAddress())) { + addressInUse.add(address.getAddress()); + inetInUse.add(address); + Node node = new Node(address); //use a random NodeId for config activeNodes + if (node.getPreferInetSocketAddress() != null) { + connectNodes.add(node); + } + } + }); + + //calculate lackSize exclude config activeNodes + int activeLackSize = p2pConfig.getMinActiveConnections() - connectingPeersCount.get(); + int size = StrictMath.max( + p2pConfig.getMinConnections() - connectingPeersCount.get() - passivePeersCount.get(), + activeLackSize); + if (p2pConfig.getMinConnections() <= activePeers.size() && activeLackSize <= 0) { + size = 0; + } + int lackSize = size; + if (lackSize > 0) { + List connectableNodes = ChannelManager.getNodeDetectService().getConnectableNodes(); + for (Node node : connectableNodes) { + // nodesInUse and inetInUse don't change in method `validNode` + if (validNode(node, nodesInUse, inetInUse, null)) { + connectNodes.add(node); + nodesInUse.add(node.getHexId()); + inetInUse.add(node.getPreferInetSocketAddress()); + lackSize -= 1; + if (lackSize <= 0) { + break; + } + } + } + } + + if (lackSize > 0) { + List connectableNodes = NodeManager.getConnectableNodes(); + // nodesInUse and inetInUse don't change in method `getNodes` + List newNodes = getNodes(nodesInUse, inetInUse, connectableNodes, lackSize); + connectNodes.addAll(newNodes); + for (Node node : newNodes) { + nodesInUse.add(node.getHexId()); + inetInUse.add(node.getPreferInetSocketAddress()); + } + lackSize -= newNodes.size(); + } + + if (lackSize > 0 && !p2pConfig.getTreeUrls().isEmpty()) { + List dnsNodes = DnsManager.getDnsNodes(); + List filtered = new ArrayList<>(); + Collections.shuffle(dnsNodes); + for (DnsNode node : dnsNodes) { + if (validNode(node, nodesInUse, inetInUse, null)) { + DnsNode copyNode = (DnsNode) node.clone(); + copyNode.setId(NetUtil.getNodeId()); + //for node1 {ipv4_1, ipv6}, node2 {ipv4_2, ipv6}, we will not connect it twice + addNode(inetInUse, node); + filtered.add(copyNode); + } + } + List newNodes = CollectionUtils.truncate(filtered, lackSize); + connectNodes.addAll(newNodes); + } + + logger.debug("Lack size:{}, connectNodes size:{}, is disconnect trigger: {}", + size, connectNodes.size(), isFilterActiveNodes); + //establish tcp connection with chose nodes by peerClient + { + connectNodes.forEach(n -> { + logger.info("Connect to peer {}", n.getPreferInetSocketAddress()); + peerClient.connectAsync(n, false); + peerClientCache.put(n.getPreferInetSocketAddress().getAddress(), + System.currentTimeMillis()); + if (!configActiveNodes.contains(n.getPreferInetSocketAddress())) { + connectingPeersCount.incrementAndGet(); + } + }); + } + } + + public List getNodes(Set nodesInUse, Set inetInUse, + List connectableNodes, int limit) { + List filtered = new ArrayList<>(); + Set dynamicInetInUse = new HashSet<>(inetInUse); + for (Node node : connectableNodes) { + if (validNode(node, nodesInUse, inetInUse, dynamicInetInUse)) { + filtered.add((Node) node.clone()); + addNode(dynamicInetInUse, node); + } + } + + filtered.sort(Comparator.comparingLong(node -> -node.getUpdateTime())); + int candidateSize = StrictMath.max(limit * 10, minCandidateSize); + if (filtered.size() > candidateSize) { + filtered = filtered.subList(0, candidateSize); + } + Collections.shuffle(filtered); + return CollectionUtils.truncate(filtered, limit); + } + + private boolean validNode(Node node, Set nodesInUse, Set inetInUse, + Set dynamicInet) { + long now = System.currentTimeMillis(); + InetSocketAddress inetSocketAddress = node.getPreferInetSocketAddress(); + InetAddress inetAddress = inetSocketAddress.getAddress(); + Long forbiddenTime = ChannelManager.getBannedNodes().getIfPresent(inetAddress); + if ((forbiddenTime != null && now <= forbiddenTime) + || (ChannelManager.getConnectionNum(inetAddress) + >= p2pConfig.getMaxConnectionsWithSameIp()) + || (node.getId() != null && nodesInUse.contains(node.getHexId())) + || (peerClientCache.getIfPresent(inetAddress) != null) + || inetInUse.contains(inetSocketAddress) + || (dynamicInet != null && dynamicInet.contains(inetSocketAddress))) { + return false; + } + return true; + } + + private void check() { + if (ChannelManager.getChannels().size() < p2pConfig.getMaxConnections()) { + return; + } + + List channels = new ArrayList<>(activePeers); + Collection peers = channels.stream() + .filter(peer -> !peer.isDisconnect()) + .filter(peer -> !peer.isTrustPeer()) + .filter(peer -> !peer.isActive()) + .collect(Collectors.toList()); + + // if len(peers) >= 0, disconnect randomly + if (!peers.isEmpty()) { + List list = new ArrayList<>(peers); + Channel peer = list.get(new Random().nextInt(peers.size())); + logger.info("Disconnect with peer randomly: {}", peer); + peer.send(new P2pDisconnectMessage(DisconnectReason.RANDOM_ELIMINATION)); + peer.close(); + } + } + + private synchronized void logActivePeers() { + logger.info("Peer stats: channels {}, activePeers {}, active {}, passive {}", + ChannelManager.getChannels().size(), activePeers.size(), activePeersCount.get(), + passivePeersCount.get()); + } + + public void triggerConnect(InetSocketAddress address) { + if (configActiveNodes.contains(address)) { + return; + } + connectingPeersCount.decrementAndGet(); + if (poolLoopExecutor.getQueue().size() >= Parameter.CONN_MAX_QUEUE_SIZE) { + logger.warn("ConnPool task' size is greater than or equal to {}", + Parameter.CONN_MAX_QUEUE_SIZE); + return; + } + try { + if (!ChannelManager.isShutdown) { + poolLoopExecutor.submit(() -> { + try { + connect(true); + } catch (Exception t) { + logger.error("Exception in poolLoopExecutor worker", t); + } + }); + } + } catch (Exception e) { + logger.warn("Submit task failed, message:{}", e.getMessage()); + } + } + + @Override + public synchronized void onConnect(Channel peer) { + if (!activePeers.contains(peer)) { + if (!peer.isActive()) { + passivePeersCount.incrementAndGet(); + } else { + activePeersCount.incrementAndGet(); + } + activePeers.add(peer); + } + logActivePeers(); + } + + @Override + public synchronized void onDisconnect(Channel peer) { + if (activePeers.contains(peer)) { + if (!peer.isActive()) { + passivePeersCount.decrementAndGet(); + } else { + activePeersCount.decrementAndGet(); + } + activePeers.remove(peer); + } + logActivePeers(); + } + + @Override + public void onMessage(Channel channel, byte[] data) { + //do nothing + } + + public void close() { + List channels = new ArrayList<>(activePeers); + try { + channels.forEach(p -> { + if (!p.isDisconnect()) { + p.send(new P2pDisconnectMessage(DisconnectReason.PEER_QUITING)); + p.close(); + } + }); + poolLoopExecutor.shutdownNow(); + disconnectExecutor.shutdownNow(); + } catch (Exception e) { + logger.warn("Problems shutting down executor", e); + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/business/upgrade/UpgradeController.java b/p2p/src/main/java/org/tron/p2p/connection/business/upgrade/UpgradeController.java new file mode 100644 index 00000000000..8e204dea08b --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/business/upgrade/UpgradeController.java @@ -0,0 +1,38 @@ +package org.tron.p2p.connection.business.upgrade; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.io.IOException; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.exception.P2pException.TypeEnum; +import org.tron.p2p.protos.Connect.CompressMessage; +import org.tron.p2p.utils.ProtoUtil; + +public class UpgradeController { + + public static byte[] codeSendData(int version, byte[] data) throws IOException { + if (!supportCompress(version)) { + return data; + } + return ProtoUtil.compressMessage(data).toByteArray(); + } + + public static byte[] decodeReceiveData(int version, byte[] data) + throws P2pException, IOException { + if (!supportCompress(version)) { + return data; + } + CompressMessage compressMessage; + try { + compressMessage = CompressMessage.parseFrom(data); + } catch (InvalidProtocolBufferException e) { + throw new P2pException(TypeEnum.PARSE_MESSAGE_FAILED, e); + } + return ProtoUtil.uncompressMessage(compressMessage); + } + + private static boolean supportCompress(int version) { + return Parameter.version >= 1 && version >= 1; + } + +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/message/Message.java b/p2p/src/main/java/org/tron/p2p/connection/message/Message.java new file mode 100644 index 00000000000..38a860a54a1 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/message/Message.java @@ -0,0 +1,78 @@ +package org.tron.p2p.connection.message; + +import org.apache.commons.lang3.ArrayUtils; +import org.tron.p2p.connection.message.base.P2pDisconnectMessage; +import org.tron.p2p.connection.message.detect.StatusMessage; +import org.tron.p2p.connection.message.handshake.HelloMessage; +import org.tron.p2p.connection.message.keepalive.PingMessage; +import org.tron.p2p.connection.message.keepalive.PongMessage; +import org.tron.p2p.exception.P2pException; + +public abstract class Message { + + protected MessageType type; + protected byte[] data; + + public Message(MessageType type, byte[] data) { + this.type = type; + this.data = data; + } + + public MessageType getType() { + return this.type; + } + + public byte[] getData() { + return this.data; + } + + public byte[] getSendData() { + return ArrayUtils.add(this.data, 0, type.getType()); + } + + public abstract boolean valid(); + + public boolean needToLog() { + return type.equals(MessageType.DISCONNECT) || type.equals(MessageType.HANDSHAKE_HELLO); + } + + public static Message parse(byte[] encode) throws P2pException { + byte type = encode[0]; + try { + byte[] data = ArrayUtils.subarray(encode, 1, encode.length); + Message message; + switch (MessageType.fromByte(type)) { + case KEEP_ALIVE_PING: + message = new PingMessage(data); + break; + case KEEP_ALIVE_PONG: + message = new PongMessage(data); + break; + case HANDSHAKE_HELLO: + message = new HelloMessage(data); + break; + case STATUS: + message = new StatusMessage(data); + break; + case DISCONNECT: + message = new P2pDisconnectMessage(data); + break; + default: + throw new P2pException(P2pException.TypeEnum.NO_SUCH_MESSAGE, "type=" + type); + } + if (!message.valid()) { + throw new P2pException(P2pException.TypeEnum.BAD_MESSAGE, "type=" + type); + } + return message; + } catch (P2pException p2pException) { + throw p2pException; + } catch (Exception e) { + throw new P2pException(P2pException.TypeEnum.BAD_MESSAGE, "type:" + type); + } + } + + @Override + public String toString() { + return "type: " + getType() + ", "; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/message/MessageType.java b/p2p/src/main/java/org/tron/p2p/connection/message/MessageType.java new file mode 100644 index 00000000000..548bb34a76e --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/message/MessageType.java @@ -0,0 +1,42 @@ +package org.tron.p2p.connection.message; + +import java.util.HashMap; +import java.util.Map; + +public enum MessageType { + + KEEP_ALIVE_PING((byte) 0xff), + + KEEP_ALIVE_PONG((byte) 0xfe), + + HANDSHAKE_HELLO((byte) 0xfd), + + STATUS((byte) 0xfc), + + DISCONNECT((byte) 0xfb), + + UNKNOWN((byte) 0x80); + + private final byte type; + + MessageType(byte type) { + this.type = type; + } + + public byte getType() { + return type; + } + + private static final Map map = new HashMap<>(); + + static { + for (MessageType value : values()) { + map.put(value.type, value); + } + } + + public static MessageType fromByte(byte type) { + MessageType typeEnum = map.get(type); + return typeEnum == null ? UNKNOWN : typeEnum; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/message/base/P2pDisconnectMessage.java b/p2p/src/main/java/org/tron/p2p/connection/message/base/P2pDisconnectMessage.java new file mode 100644 index 00000000000..28460676dd4 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/message/base/P2pDisconnectMessage.java @@ -0,0 +1,39 @@ +package org.tron.p2p.connection.message.base; + +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.protos.Connect; +import org.tron.p2p.protos.Connect.DisconnectReason; + + +public class P2pDisconnectMessage extends Message { + + private Connect.P2pDisconnectMessage p2pDisconnectMessage; + + public P2pDisconnectMessage(byte[] data) throws Exception { + super(MessageType.DISCONNECT, data); + this.p2pDisconnectMessage = Connect.P2pDisconnectMessage.parseFrom(data); + } + + public P2pDisconnectMessage(DisconnectReason disconnectReason) { + super(MessageType.DISCONNECT, null); + this.p2pDisconnectMessage = Connect.P2pDisconnectMessage.newBuilder() + .setReason(disconnectReason).build(); + this.data = p2pDisconnectMessage.toByteArray(); + } + + private DisconnectReason getReason() { + return p2pDisconnectMessage.getReason(); + } + + @Override + public boolean valid() { + return true; + } + + @Override + public String toString() { + return new StringBuilder().append(super.toString()).append("reason: ") + .append(getReason()).toString(); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/message/detect/StatusMessage.java b/p2p/src/main/java/org/tron/p2p/connection/message/detect/StatusMessage.java new file mode 100644 index 00000000000..3cadb4620dc --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/message/detect/StatusMessage.java @@ -0,0 +1,61 @@ +package org.tron.p2p.connection.message.detect; + +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.discover.Node; +import org.tron.p2p.protos.Connect; +import org.tron.p2p.protos.Discover; +import org.tron.p2p.utils.NetUtil; + +public class StatusMessage extends Message { + private Connect.StatusMessage statusMessage; + + public StatusMessage(byte[] data) throws Exception { + super(MessageType.STATUS, data); + this.statusMessage = Connect.StatusMessage.parseFrom(data); + } + + public StatusMessage() { + super(MessageType.STATUS, null); + Discover.Endpoint endpoint = Parameter.getHomeNode(); + this.statusMessage = Connect.StatusMessage.newBuilder() + .setFrom(endpoint) + .setMaxConnections(Parameter.p2pConfig.getMaxConnections()) + .setCurrentConnections(ChannelManager.getChannels().size()) + .setNetworkId(Parameter.p2pConfig.getNetworkId()) + .setTimestamp(System.currentTimeMillis()).build(); + this.data = statusMessage.toByteArray(); + } + + public int getNetworkId() { + return this.statusMessage.getNetworkId(); + } + + public int getVersion() { + return this.statusMessage.getVersion(); + } + + public int getRemainConnections() { + return this.statusMessage.getMaxConnections() - this.statusMessage.getCurrentConnections(); + } + + public long getTimestamp() { + return this.statusMessage.getTimestamp(); + } + + public Node getFrom() { + return NetUtil.getNode(statusMessage.getFrom()); + } + + @Override + public String toString() { + return "[StatusMessage: " + statusMessage; + } + + @Override + public boolean valid() { + return NetUtil.validNode(getFrom()); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/message/handshake/HelloMessage.java b/p2p/src/main/java/org/tron/p2p/connection/message/handshake/HelloMessage.java new file mode 100644 index 00000000000..726379dc139 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/message/handshake/HelloMessage.java @@ -0,0 +1,64 @@ +package org.tron.p2p.connection.message.handshake; + +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.business.handshake.DisconnectCode; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.discover.Node; +import org.tron.p2p.protos.Connect; +import org.tron.p2p.protos.Discover; +import org.tron.p2p.utils.NetUtil; + +public class HelloMessage extends Message { + + private Connect.HelloMessage helloMessage; + + public HelloMessage(byte[] data) throws Exception { + super(MessageType.HANDSHAKE_HELLO, data); + this.helloMessage = Connect.HelloMessage.parseFrom(data); + } + + public HelloMessage(DisconnectCode code, long time) { + super(MessageType.HANDSHAKE_HELLO, null); + Discover.Endpoint endpoint = Parameter.getHomeNode(); + this.helloMessage = Connect.HelloMessage.newBuilder() + .setFrom(endpoint) + .setNetworkId(Parameter.p2pConfig.getNetworkId()) + .setCode(code.getValue()) + .setVersion(Parameter.version) + .setTimestamp(time).build(); + this.data = helloMessage.toByteArray(); + } + + public int getNetworkId() { + return this.helloMessage.getNetworkId(); + } + + public int getVersion() { + return this.helloMessage.getVersion(); + } + + public int getCode() { + return this.helloMessage.getCode(); + } + + public long getTimestamp() { + return this.helloMessage.getTimestamp(); + } + + public Node getFrom() { + return NetUtil.getNode(helloMessage.getFrom()); + } + + @Override + public String toString() { + return "HelloMessage networkId: " + getNetworkId() + + ", version: " + getVersion() + + ", code: " + getCode(); + } + + @Override + public boolean valid() { + return NetUtil.validNode(getFrom()); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/message/keepalive/PingMessage.java b/p2p/src/main/java/org/tron/p2p/connection/message/keepalive/PingMessage.java new file mode 100644 index 00000000000..8191b5e72f1 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/message/keepalive/PingMessage.java @@ -0,0 +1,33 @@ +package org.tron.p2p.connection.message.keepalive; + +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.protos.Connect; + +public class PingMessage extends Message { + + private Connect.KeepAliveMessage keepAliveMessage; + + public PingMessage(byte[] data) throws Exception { + super(MessageType.KEEP_ALIVE_PING, data); + this.keepAliveMessage = Connect.KeepAliveMessage.parseFrom(data); + } + + public PingMessage() { + super(MessageType.KEEP_ALIVE_PING, null); + this.keepAliveMessage = Connect.KeepAliveMessage.newBuilder() + .setTimestamp(System.currentTimeMillis()).build(); + this.data = this.keepAliveMessage.toByteArray(); + } + + public long getTimeStamp() { + return this.keepAliveMessage.getTimestamp(); + } + + @Override + public boolean valid() { + return getTimeStamp() > 0 + && getTimeStamp() <= System.currentTimeMillis() + Parameter.NETWORK_TIME_DIFF; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/message/keepalive/PongMessage.java b/p2p/src/main/java/org/tron/p2p/connection/message/keepalive/PongMessage.java new file mode 100644 index 00000000000..b3689bea93b --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/message/keepalive/PongMessage.java @@ -0,0 +1,33 @@ +package org.tron.p2p.connection.message.keepalive; + +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.protos.Connect; + +public class PongMessage extends Message { + + private Connect.KeepAliveMessage keepAliveMessage; + + public PongMessage(byte[] data) throws Exception { + super(MessageType.KEEP_ALIVE_PONG, data); + this.keepAliveMessage = Connect.KeepAliveMessage.parseFrom(data); + } + + public PongMessage() { + super(MessageType.KEEP_ALIVE_PONG, null); + this.keepAliveMessage = Connect.KeepAliveMessage.newBuilder() + .setTimestamp(System.currentTimeMillis()).build(); + this.data = this.keepAliveMessage.toByteArray(); + } + + public long getTimeStamp() { + return this.keepAliveMessage.getTimestamp(); + } + + @Override + public boolean valid() { + return getTimeStamp() > 0 + && getTimeStamp() <= System.currentTimeMillis() + Parameter.NETWORK_TIME_DIFF; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/socket/MessageHandler.java b/p2p/src/main/java/org/tron/p2p/connection/socket/MessageHandler.java new file mode 100644 index 00000000000..797197f0fad --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/socket/MessageHandler.java @@ -0,0 +1,90 @@ +package org.tron.p2p.connection.socket; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.connection.business.upgrade.UpgradeController; +import org.tron.p2p.connection.message.base.P2pDisconnectMessage; +import org.tron.p2p.connection.message.detect.StatusMessage; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.protos.Connect.DisconnectReason; +import org.tron.p2p.utils.ByteArray; + +@Slf4j(topic = "net") +public class MessageHandler extends ByteToMessageDecoder { + + private final Channel channel; + + public MessageHandler(Channel channel) { + this.channel = channel; + } + + @Override + public void handlerAdded(ChannelHandlerContext ctx) { + } + + @Override + public void channelActive(ChannelHandlerContext ctx) { + logger.debug("Channel active, {}", ctx.channel().remoteAddress()); + channel.setChannelHandlerContext(ctx); + if (channel.isActive()) { + if (channel.isDiscoveryMode()) { + channel.send(new StatusMessage()); + } else { + ChannelManager.getHandshakeService().startHandshake(channel); + } + } + } + + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List out) { + byte[] data = new byte[buffer.readableBytes()]; + buffer.readBytes(data); + try { + if (channel.isFinishHandshake()) { + data = UpgradeController.decodeReceiveData(channel.getVersion(), data); + } + ChannelManager.processMessage(channel, data); + } catch (Exception e) { + if (e instanceof P2pException) { + P2pException pe = (P2pException) e; + DisconnectReason disconnectReason; + switch (pe.getType()) { + case EMPTY_MESSAGE: + disconnectReason = DisconnectReason.EMPTY_MESSAGE; + break; + case BAD_PROTOCOL: + disconnectReason = DisconnectReason.BAD_PROTOCOL; + break; + case NO_SUCH_MESSAGE: + disconnectReason = DisconnectReason.NO_SUCH_MESSAGE; + break; + case BAD_MESSAGE: + case PARSE_MESSAGE_FAILED: + case MESSAGE_WITH_WRONG_LENGTH: + case TYPE_ALREADY_REGISTERED: + disconnectReason = DisconnectReason.BAD_MESSAGE; + break; + default: + disconnectReason = DisconnectReason.UNKNOWN; + } + channel.send(new P2pDisconnectMessage(disconnectReason)); + } + channel.processException(e); + } catch (Throwable t) { + logger.error("Decode message from {} failed, message:{}", channel.getInetSocketAddress(), + ByteArray.toHexString(data)); + throw t; + } + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + channel.processException(cause); + } + +} \ No newline at end of file diff --git a/p2p/src/main/java/org/tron/p2p/connection/socket/P2pChannelInitializer.java b/p2p/src/main/java/org/tron/p2p/connection/socket/P2pChannelInitializer.java new file mode 100644 index 00000000000..31b2ea302ef --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/socket/P2pChannelInitializer.java @@ -0,0 +1,62 @@ +package org.tron.p2p.connection.socket; + +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; +import io.netty.channel.FixedRecvByteBufAllocator; +import io.netty.channel.socket.nio.NioSocketChannel; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; + +@Slf4j(topic = "net") +public class P2pChannelInitializer extends ChannelInitializer { + + private final String remoteId; + + //only be true when channel is activated by detect service + private boolean peerDiscoveryMode = false; + + private boolean trigger = true; + + public P2pChannelInitializer(String remoteId, boolean peerDiscoveryMode, boolean trigger) { + this.remoteId = remoteId; + this.peerDiscoveryMode = peerDiscoveryMode; + this.trigger = trigger; + } + + @Override + public void initChannel(NioSocketChannel ch) { + try { + final Channel channel = new Channel(); + channel.init(ch.pipeline(), remoteId, peerDiscoveryMode); + + // limit the size of receiving buffer to 1024 + ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(256 * 1024)); + ch.config().setOption(ChannelOption.SO_RCVBUF, 256 * 1024); + ch.config().setOption(ChannelOption.SO_BACKLOG, 1024); + + // be aware of channel closing + ch.closeFuture().addListener((ChannelFutureListener) future -> { + channel.setDisconnect(true); + if (channel.isDiscoveryMode()) { + ChannelManager.getNodeDetectService().notifyDisconnect(channel); + } else { + try { + logger.info("Close channel:{}", channel.getInetSocketAddress()); + ChannelManager.notifyDisconnect(channel); + } finally { + if (channel.getInetSocketAddress() != null && channel.isActive() && trigger) { + ChannelManager.triggerConnect(channel.getInetSocketAddress()); + } + } + } + }); + + } catch (Exception e) { + logger.error("Unexpected initChannel error", e); + } + } + +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/socket/P2pProtobufVarint32FrameDecoder.java b/p2p/src/main/java/org/tron/p2p/connection/socket/P2pProtobufVarint32FrameDecoder.java new file mode 100644 index 00000000000..4493551da96 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/socket/P2pProtobufVarint32FrameDecoder.java @@ -0,0 +1,98 @@ +package org.tron.p2p.connection.socket; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; +import io.netty.handler.codec.CorruptedFrameException; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.message.base.P2pDisconnectMessage; +import org.tron.p2p.protos.Connect.DisconnectReason; + +@Slf4j(topic = "net") +public class P2pProtobufVarint32FrameDecoder extends ByteToMessageDecoder { + + private final Channel channel; + + public P2pProtobufVarint32FrameDecoder(Channel channel) { + this.channel = channel; + } + + private static int readRawVarint32(ByteBuf buffer) { + if (!buffer.isReadable()) { + return 0; + } + buffer.markReaderIndex(); + byte tmp = buffer.readByte(); + if (tmp >= 0) { + return tmp; + } else { + int result = tmp & 127; + if (!buffer.isReadable()) { + buffer.resetReaderIndex(); + return 0; + } + if ((tmp = buffer.readByte()) >= 0) { + result |= tmp << 7; + } else { + result |= (tmp & 127) << 7; + if (!buffer.isReadable()) { + buffer.resetReaderIndex(); + return 0; + } + if ((tmp = buffer.readByte()) >= 0) { + result |= tmp << 14; + } else { + result |= (tmp & 127) << 14; + if (!buffer.isReadable()) { + buffer.resetReaderIndex(); + return 0; + } + if ((tmp = buffer.readByte()) >= 0) { + result |= tmp << 21; + } else { + result |= (tmp & 127) << 21; + if (!buffer.isReadable()) { + buffer.resetReaderIndex(); + return 0; + } + result |= (tmp = buffer.readByte()) << 28; + if (tmp < 0) { + throw new CorruptedFrameException("malformed varint."); + } + } + } + } + return result; + } + } + + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) { + in.markReaderIndex(); + int preIndex = in.readerIndex(); + int length = readRawVarint32(in); + if (length >= Parameter.MAX_MESSAGE_LENGTH) { + logger.warn("Receive a big msg or not encoded msg, host : {}, msg length is : {}", + ctx.channel().remoteAddress(), length); + in.clear(); + channel.send(new P2pDisconnectMessage(DisconnectReason.BAD_MESSAGE)); + channel.close(); + return; + } + if (preIndex == in.readerIndex()) { + return; + } + if (length < 0) { + throw new CorruptedFrameException("negative length: " + length); + } + + if (in.readableBytes() < length) { + in.resetReaderIndex(); + } else { + out.add(in.readRetainedSlice(length)); + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/socket/PeerClient.java b/p2p/src/main/java/org/tron/p2p/connection/socket/PeerClient.java new file mode 100644 index 00000000000..6a49e89d200 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/socket/PeerClient.java @@ -0,0 +1,103 @@ +package org.tron.p2p.connection.socket; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelOption; +import io.netty.channel.DefaultMessageSizeEstimator; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioSocketChannel; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.bouncycastle.util.encoders.Hex; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.discover.Node; +import org.tron.p2p.utils.NetUtil; + +@Slf4j(topic = "net") +public class PeerClient { + + private EventLoopGroup workerGroup; + + public void init() { + workerGroup = new NioEventLoopGroup(0, + BasicThreadFactory.builder().namingPattern("peerClient-%d").build()); + } + + public void close() { + workerGroup.shutdownGracefully(); + workerGroup.terminationFuture().syncUninterruptibly(); + } + + public void connect(String host, int port, String remoteId) { + try { + ChannelFuture f = connectAsync(host, port, remoteId, false, false); + if (f != null) { + f.sync().channel().closeFuture().sync(); + } + } catch (Exception e) { + logger.warn("PeerClient can't connect to {}:{} ({})", host, port, e.getMessage()); + } + } + + public ChannelFuture connect(Node node, ChannelFutureListener future) { + ChannelFuture channelFuture = connectAsync( + node.getPreferInetSocketAddress().getAddress().getHostAddress(), + node.getPort(), + node.getId() == null ? Hex.toHexString(NetUtil.getNodeId()) : node.getHexId(), false, + false); + if (ChannelManager.isShutdown) { + return null; + } + if (channelFuture != null && future != null) { + channelFuture.addListener(future); + } + return channelFuture; + } + + public ChannelFuture connectAsync(Node node, boolean discoveryMode) { + ChannelFuture channelFuture = + connectAsync(node.getPreferInetSocketAddress().getAddress().getHostAddress(), + node.getPort(), + node.getId() == null ? Hex.toHexString(NetUtil.getNodeId()) : node.getHexId(), + discoveryMode, true); + if (ChannelManager.isShutdown) { + return null; + } + if (channelFuture != null) { + channelFuture.addListener((ChannelFutureListener) future -> { + if (!future.isSuccess()) { + logger.warn("Connect to peer {} fail, cause:{}", node.getPreferInetSocketAddress(), + future.cause().getMessage()); + future.channel().close(); + if (!discoveryMode) { + ChannelManager.triggerConnect(node.getPreferInetSocketAddress()); + } + } + }); + } + return channelFuture; + } + + private ChannelFuture connectAsync(String host, int port, String remoteId, + boolean discoveryMode, boolean trigger) { + + P2pChannelInitializer p2pChannelInitializer = new P2pChannelInitializer(remoteId, + discoveryMode, trigger); + + Bootstrap b = new Bootstrap(); + b.group(workerGroup); + b.channel(NioSocketChannel.class); + b.option(ChannelOption.SO_KEEPALIVE, true); + b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT); + b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Parameter.NODE_CONNECTION_TIMEOUT); + b.remoteAddress(host, port); + b.handler(p2pChannelInitializer); + if (ChannelManager.isShutdown) { + return null; + } + return b.connect(); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/connection/socket/PeerServer.java b/p2p/src/main/java/org/tron/p2p/connection/socket/PeerServer.java new file mode 100644 index 00000000000..6c24dd71b72 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/connection/socket/PeerServer.java @@ -0,0 +1,79 @@ +package org.tron.p2p.connection.socket; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelOption; +import io.netty.channel.DefaultMessageSizeEstimator; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.logging.LoggingHandler; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.tron.p2p.base.Parameter; + +@Slf4j(topic = "net") +public class PeerServer { + + private ChannelFuture channelFuture; + private boolean listening; + + public void init() { + int port = Parameter.p2pConfig.getPort(); + if (port > 0) { + new Thread(() -> start(port), "PeerServer").start(); + } + } + + public void close() { + if (listening && channelFuture != null && channelFuture.channel().isOpen()) { + try { + logger.info("Closing TCP server..."); + channelFuture.channel().close().sync(); + } catch (Exception e) { + logger.warn("Closing TCP server failed.", e); + } + } + } + + public void start(int port) { + EventLoopGroup bossGroup = new NioEventLoopGroup(1, + BasicThreadFactory.builder().namingPattern("peerBoss").build()); + //if threads = 0, it is number of core * 2 + EventLoopGroup workerGroup = new NioEventLoopGroup(Parameter.TCP_NETTY_WORK_THREAD_NUM, + BasicThreadFactory.builder().namingPattern("peerWorker-%d").build()); + P2pChannelInitializer p2pChannelInitializer = new P2pChannelInitializer("", false, true); + try { + ServerBootstrap b = new ServerBootstrap(); + + b.group(bossGroup, workerGroup); + b.channel(NioServerSocketChannel.class); + + b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT); + b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Parameter.NODE_CONNECTION_TIMEOUT); + + b.handler(new LoggingHandler()); + b.childHandler(p2pChannelInitializer); + + // Start the client. + logger.info("TCP listener started, bind port {}", port); + + channelFuture = b.bind(port).sync(); + + listening = true; + + // Wait until the connection is closed. + channelFuture.channel().closeFuture().sync(); + + logger.info("TCP listener closed"); + + } catch (Exception e) { + logger.error("Start TCP server failed", e); + } finally { + workerGroup.shutdownGracefully(); + bossGroup.shutdownGracefully(); + listening = false; + } + } + +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/DiscoverService.java b/p2p/src/main/java/org/tron/p2p/discover/DiscoverService.java new file mode 100644 index 00000000000..4acff74ec69 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/DiscoverService.java @@ -0,0 +1,25 @@ +package org.tron.p2p.discover; + +import java.util.List; +import org.tron.p2p.discover.socket.EventHandler; +import org.tron.p2p.discover.socket.UdpEvent; + +public interface DiscoverService extends EventHandler { + + void init(); + + void close(); + + List getConnectableNodes(); + + List getTableNodes(); + + List getAllNodes(); + + Node getPublicHomeNode(); + + void channelActivated(); + + void handleEvent(UdpEvent event); + +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/Node.java b/p2p/src/main/java/org/tron/p2p/discover/Node.java new file mode 100644 index 00000000000..14edce3ad1f --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/Node.java @@ -0,0 +1,197 @@ +package org.tron.p2p.discover; + +import java.io.Serializable; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.bouncycastle.util.encoders.Hex; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.utils.NetUtil; + +@Slf4j(topic = "net") +public class Node implements Serializable, Cloneable { + + private static final long serialVersionUID = -4267600517925770636L; + + @Setter + @Getter + private byte[] id; + + @Getter + protected String hostV4; + + @Getter + protected String hostV6; + + @Setter + @Getter + protected int port; + + @Setter + private int bindPort; + + @Setter + private int p2pVersion; + + @Getter + private long updateTime; + + public Node(InetSocketAddress address) { + this.id = NetUtil.getNodeId(); + if (address.getAddress() instanceof Inet4Address) { + this.hostV4 = address.getAddress().getHostAddress(); + } else { + this.hostV6 = address.getAddress().getHostAddress(); + } + this.port = address.getPort(); + this.bindPort = port; + this.updateTime = System.currentTimeMillis(); + formatHostV6(); + } + + public Node(byte[] id, String hostV4, String hostV6, int port) { + this.id = id; + this.hostV4 = hostV4; + this.hostV6 = hostV6; + this.port = port; + this.bindPort = port; + this.updateTime = System.currentTimeMillis(); + formatHostV6(); + } + + public Node(byte[] id, String hostV4, String hostV6, int port, int bindPort) { + this.id = id; + this.hostV4 = hostV4; + this.hostV6 = hostV6; + this.port = port; + this.bindPort = bindPort; + this.updateTime = System.currentTimeMillis(); + formatHostV6(); + } + + public void updateHostV4(String hostV4) { + if (StringUtils.isEmpty(this.hostV4) && StringUtils.isNotEmpty(hostV4)) { + logger.info("update hostV4:{} with hostV6:{}", hostV4, this.hostV6); + this.hostV4 = hostV4; + } + } + + public void updateHostV6(String hostV6) { + if (StringUtils.isEmpty(this.hostV6) && StringUtils.isNotEmpty(hostV6)) { + logger.info("update hostV6:{} with hostV4:{}", hostV6, this.hostV4); + this.hostV6 = hostV6; + } + } + + //use standard ipv6 format + private void formatHostV6() { + if (StringUtils.isNotEmpty(this.hostV6)) { + // Only canonicalize valid IPv6 literals. a non-literal triggers a blocking JVM DNS lookup + // on the calling (netty I/O) thread + if (!NetUtil.validIpV6(this.hostV6)) { + this.hostV6 = null; + return; + } + InetAddress address = new InetSocketAddress(hostV6, port).getAddress(); + this.hostV6 = address == null ? null : address.getHostAddress(); + } + } + + public boolean isConnectible(int argsP2PVersion) { + return port == bindPort && p2pVersion == argsP2PVersion; + } + + public InetSocketAddress getPreferInetSocketAddress() { + if (StringUtils.isNotEmpty(hostV4) && StringUtils.isNotEmpty(Parameter.p2pConfig.getIp())) { + return getInetSocketAddressV4(); + } else if (StringUtils.isNotEmpty(hostV6) && StringUtils.isNotEmpty( + Parameter.p2pConfig.getIpv6())) { + return getInetSocketAddressV6(); + } else { + return null; + } + } + + public String getHexId() { + return id == null ? null : Hex.toHexString(id); + } + + public String getHexIdShort() { + return getIdShort(getHexId()); + } + + public String getHostKey() { + return getPreferInetSocketAddress().getAddress().getHostAddress(); + } + + public String getIdString() { + if (id == null) { + return null; + } + return new String(id); + } + + public void touch() { + updateTime = System.currentTimeMillis(); + } + + @Override + public String toString() { + return "Node{" + " hostV4='" + hostV4 + '\'' + ", hostV6='" + hostV6 + '\'' + ", port=" + port + + ", id=\'" + (id == null ? "null" : Hex.toHexString(id)) + "\'}"; + } + + public String format() { + return "Node{" + " hostV4='" + hostV4 + '\'' + ", hostV6='" + hostV6 + '\'' + ", port=" + port + + '}'; + } + + @Override + public int hashCode() { + return this.format().hashCode(); + } + + @Override + public boolean equals(Object o) { + if (o == null) { + return false; + } + + if (o == this) { + return true; + } + + if (o.getClass() == getClass()) { + return StringUtils.equals(getIdString(), ((Node) o).getIdString()); + } + + return false; + } + + private String getIdShort(String hexId) { + return hexId == null ? "" : hexId.substring(0, 8); + } + + public InetSocketAddress getInetSocketAddressV4() { + return StringUtils.isNotEmpty(hostV4) ? new InetSocketAddress(hostV4, port) : null; + } + + public InetSocketAddress getInetSocketAddressV6() { + return StringUtils.isNotEmpty(hostV6) ? new InetSocketAddress(hostV6, port) : null; + } + + @Override + public Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException ignored) { + // Node implements Cloneable, so super.clone() cannot throw here. + // Fall through to the null return, preserving the original behaviour. + } + return null; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/NodeManager.java b/p2p/src/main/java/org/tron/p2p/discover/NodeManager.java new file mode 100644 index 00000000000..e995ff6bb8e --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/NodeManager.java @@ -0,0 +1,47 @@ +package org.tron.p2p.discover; + +import java.util.List; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.protocol.kad.KadService; +import org.tron.p2p.discover.socket.DiscoverServer; + +public class NodeManager { + + private static DiscoverService discoverService; + private static DiscoverServer discoverServer; + + public static void init() { + discoverService = new KadService(); + discoverService.init(); + if (Parameter.p2pConfig.isDiscoverEnable()) { + discoverServer = new DiscoverServer(); + discoverServer.init(discoverService); + } + } + + public static void close() { + if (discoverService != null) { + discoverService.close(); + } + if (discoverServer != null) { + discoverServer.close(); + } + } + + public static List getConnectableNodes() { + return discoverService.getConnectableNodes(); + } + + public static Node getHomeNode() { + return discoverService.getPublicHomeNode(); + } + + public static List getTableNodes() { + return discoverService.getTableNodes(); + } + + public static List getAllNodes() { + return discoverService.getAllNodes(); + } + +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/message/Message.java b/p2p/src/main/java/org/tron/p2p/discover/message/Message.java new file mode 100644 index 00000000000..592b7b133be --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/message/Message.java @@ -0,0 +1,69 @@ +package org.tron.p2p.discover.message; + +import org.apache.commons.lang3.ArrayUtils; +import org.tron.p2p.discover.message.kad.FindNodeMessage; +import org.tron.p2p.discover.message.kad.NeighborsMessage; +import org.tron.p2p.discover.message.kad.PingMessage; +import org.tron.p2p.discover.message.kad.PongMessage; +import org.tron.p2p.exception.P2pException; + +public abstract class Message { + protected MessageType type; + protected byte[] data; + + protected Message(MessageType type, byte[] data) { + this.type = type; + this.data = data; + } + + public static Message parse(byte[] encode) throws Exception { + byte type = encode[0]; + byte[] data = ArrayUtils.subarray(encode, 1, encode.length); + Message message; + switch (MessageType.fromByte(type)) { + case KAD_PING: + message = new PingMessage(data); + break; + case KAD_PONG: + message = new PongMessage(data); + break; + case KAD_FIND_NODE: + message = new FindNodeMessage(data); + break; + case KAD_NEIGHBORS: + message = new NeighborsMessage(data); + break; + default: + throw new P2pException(P2pException.TypeEnum.NO_SUCH_MESSAGE, "type=" + type); + } + if (!message.valid()) { + throw new P2pException(P2pException.TypeEnum.BAD_MESSAGE, "type=" + type); + } + return message; + } + + public MessageType getType() { + return this.type; + } + + public byte[] getData() { + return this.data; + } + + public byte[] getSendData() { + return ArrayUtils.add(this.data, 0, type.getType()); + } + + public abstract boolean valid(); + + @Override + public String toString() { + return "[Message Type: " + getType() + ", len: " + (data == null ? 0 : data.length) + "]"; + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/message/MessageType.java b/p2p/src/main/java/org/tron/p2p/discover/message/MessageType.java new file mode 100644 index 00000000000..09d16a45a8b --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/message/MessageType.java @@ -0,0 +1,41 @@ +package org.tron.p2p.discover.message; + +import java.util.HashMap; +import java.util.Map; + +public enum MessageType { + + KAD_PING((byte) 0x01), + + KAD_PONG((byte) 0x02), + + KAD_FIND_NODE((byte) 0x03), + + KAD_NEIGHBORS((byte) 0x04), + + UNKNOWN((byte) 0xFF); + + private final byte type; + + MessageType(byte type) { + this.type = type; + } + + public byte getType() { + return type; + } + + private static final Map map = new HashMap<>(); + + static { + for (MessageType value : values()) { + map.put(value.type, value); + } + } + + public static MessageType fromByte(byte type) { + MessageType typeEnum = map.get(type); + return typeEnum == null ? UNKNOWN : typeEnum; + } + +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/message/kad/FindNodeMessage.java b/p2p/src/main/java/org/tron/p2p/discover/message/kad/FindNodeMessage.java new file mode 100644 index 00000000000..d3f812ded0f --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/message/kad/FindNodeMessage.java @@ -0,0 +1,55 @@ +package org.tron.p2p.discover.message.kad; + +import com.google.protobuf.ByteString; +import org.tron.p2p.base.Constant; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.MessageType; +import org.tron.p2p.protos.Discover; +import org.tron.p2p.protos.Discover.Endpoint; +import org.tron.p2p.utils.NetUtil; + +public class FindNodeMessage extends KadMessage { + + private Discover.FindNeighbours findNeighbours; + + public FindNodeMessage(byte[] data) throws Exception { + super(MessageType.KAD_FIND_NODE, data); + this.findNeighbours = Discover.FindNeighbours.parseFrom(data); + } + + public FindNodeMessage(Node from, byte[] targetId) { + super(MessageType.KAD_FIND_NODE, null); + Endpoint fromEndpoint = getEndpointFromNode(from); + this.findNeighbours = Discover.FindNeighbours.newBuilder() + .setFrom(fromEndpoint) + .setTargetId(ByteString.copyFrom(targetId)) + .setTimestamp(System.currentTimeMillis()) + .build(); + this.data = this.findNeighbours.toByteArray(); + } + + public byte[] getTargetId() { + return this.findNeighbours.getTargetId().toByteArray(); + } + + @Override + public long getTimestamp() { + return this.findNeighbours.getTimestamp(); + } + + @Override + public Node getFrom() { + return NetUtil.getNode(findNeighbours.getFrom()); + } + + @Override + public String toString() { + return "[findNeighbours: " + findNeighbours; + } + + @Override + public boolean valid() { + return NetUtil.validNode(getFrom()) + && getTargetId().length == Constant.NODE_ID_LEN; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/message/kad/KadMessage.java b/p2p/src/main/java/org/tron/p2p/discover/message/kad/KadMessage.java new file mode 100644 index 00000000000..d4506db5b78 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/message/kad/KadMessage.java @@ -0,0 +1,35 @@ +package org.tron.p2p.discover.message.kad; + +import com.google.protobuf.ByteString; +import org.apache.commons.lang3.StringUtils; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.Message; +import org.tron.p2p.discover.message.MessageType; +import org.tron.p2p.protos.Discover.Endpoint; +import org.tron.p2p.utils.ByteArray; + +public abstract class KadMessage extends Message { + + protected KadMessage(MessageType type, byte[] data) { + super(type, data); + } + + public abstract Node getFrom(); + + public abstract long getTimestamp(); + + public static Endpoint getEndpointFromNode(Node node) { + Endpoint.Builder builder = Endpoint.newBuilder() + .setPort(node.getPort()); + if (node.getId() != null) { + builder.setNodeId(ByteString.copyFrom(node.getId())); + } + if (StringUtils.isNotEmpty(node.getHostV4())) { + builder.setAddress(ByteString.copyFrom(ByteArray.fromString(node.getHostV4()))); + } + if (StringUtils.isNotEmpty(node.getHostV6())) { + builder.setAddressIpv6(ByteString.copyFrom(ByteArray.fromString(node.getHostV6()))); + } + return builder.build(); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/message/kad/NeighborsMessage.java b/p2p/src/main/java/org/tron/p2p/discover/message/kad/NeighborsMessage.java new file mode 100644 index 00000000000..37fd4d67271 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/message/kad/NeighborsMessage.java @@ -0,0 +1,80 @@ +package org.tron.p2p.discover.message.kad; + +import java.util.ArrayList; +import java.util.List; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.MessageType; +import org.tron.p2p.discover.protocol.kad.table.KademliaOptions; +import org.tron.p2p.protos.Discover; +import org.tron.p2p.protos.Discover.Endpoint; +import org.tron.p2p.protos.Discover.Neighbours; +import org.tron.p2p.protos.Discover.Neighbours.Builder; +import org.tron.p2p.utils.NetUtil; + +public class NeighborsMessage extends KadMessage { + + private Discover.Neighbours neighbours; + + public NeighborsMessage(byte[] data) throws Exception { + super(MessageType.KAD_NEIGHBORS, data); + this.neighbours = Discover.Neighbours.parseFrom(data); + } + + public NeighborsMessage(Node from, List neighbours, long sequence) { + super(MessageType.KAD_NEIGHBORS, null); + Builder builder = Neighbours.newBuilder() + .setTimestamp(sequence); + + neighbours.forEach(neighbour -> { + Endpoint endpoint = getEndpointFromNode(neighbour); + builder.addNeighbours(endpoint); + }); + + Endpoint fromEndpoint = getEndpointFromNode(from); + + builder.setFrom(fromEndpoint); + + this.neighbours = builder.build(); + + this.data = this.neighbours.toByteArray(); + } + + public List getNodes() { + List nodes = new ArrayList<>(); + neighbours.getNeighboursList().forEach(n -> nodes.add(NetUtil.getNode(n))); + return nodes; + } + + @Override + public long getTimestamp() { + return this.neighbours.getTimestamp(); + } + + @Override + public Node getFrom() { + return NetUtil.getNode(neighbours.getFrom()); + } + + @Override + public String toString() { + return "[neighbours: " + neighbours; + } + + @Override + public boolean valid() { + if (!NetUtil.validNode(getFrom())) { + return false; + } + if (getNodes().size() > 0) { + if (getNodes().size() > KademliaOptions.BUCKET_SIZE) { + return false; + } + for (Node node : getNodes()) { + if (!NetUtil.validNode(node)) { + return false; + } + } + } + return true; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/message/kad/PingMessage.java b/p2p/src/main/java/org/tron/p2p/discover/message/kad/PingMessage.java new file mode 100644 index 00000000000..e1cca85aa79 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/message/kad/PingMessage.java @@ -0,0 +1,59 @@ +package org.tron.p2p.discover.message.kad; + +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.MessageType; +import org.tron.p2p.protos.Discover; +import org.tron.p2p.protos.Discover.Endpoint; +import org.tron.p2p.utils.NetUtil; + +public class PingMessage extends KadMessage { + + private Discover.PingMessage pingMessage; + + public PingMessage(byte[] data) throws Exception { + super(MessageType.KAD_PING, data); + this.pingMessage = Discover.PingMessage.parseFrom(data); + } + + public PingMessage(Node from, Node to) { + super(MessageType.KAD_PING, null); + Endpoint fromEndpoint = getEndpointFromNode(from); + Endpoint toEndpoint = getEndpointFromNode(to); + this.pingMessage = Discover.PingMessage.newBuilder() + .setVersion(Parameter.p2pConfig.getNetworkId()) + .setFrom(fromEndpoint) + .setTo(toEndpoint) + .setTimestamp(System.currentTimeMillis()) + .build(); + this.data = this.pingMessage.toByteArray(); + } + + public int getNetworkId() { + return this.pingMessage.getVersion(); + } + + public Node getTo() { + return NetUtil.getNode(this.pingMessage.getTo()); + } + + @Override + public long getTimestamp() { + return this.pingMessage.getTimestamp(); + } + + @Override + public Node getFrom() { + return NetUtil.getNode(pingMessage.getFrom()); + } + + @Override + public String toString() { + return "[pingMessage: " + pingMessage; + } + + @Override + public boolean valid() { + return NetUtil.validNode(getFrom()); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/message/kad/PongMessage.java b/p2p/src/main/java/org/tron/p2p/discover/message/kad/PongMessage.java new file mode 100644 index 00000000000..8ae80fbb0f6 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/message/kad/PongMessage.java @@ -0,0 +1,53 @@ +package org.tron.p2p.discover.message.kad; + +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.MessageType; +import org.tron.p2p.protos.Discover; +import org.tron.p2p.protos.Discover.Endpoint; +import org.tron.p2p.utils.NetUtil; + +public class PongMessage extends KadMessage { + + private Discover.PongMessage pongMessage; + + public PongMessage(byte[] data) throws Exception { + super(MessageType.KAD_PONG, data); + this.pongMessage = Discover.PongMessage.parseFrom(data); + } + + public PongMessage(Node from) { + super(MessageType.KAD_PONG, null); + Endpoint toEndpoint = getEndpointFromNode(from); + this.pongMessage = Discover.PongMessage.newBuilder() + .setFrom(toEndpoint) + .setEcho(Parameter.p2pConfig.getNetworkId()) + .setTimestamp(System.currentTimeMillis()) + .build(); + this.data = this.pongMessage.toByteArray(); + } + + public int getNetworkId() { + return this.pongMessage.getEcho(); + } + + @Override + public long getTimestamp() { + return this.pongMessage.getTimestamp(); + } + + @Override + public Node getFrom() { + return NetUtil.getNode(pongMessage.getFrom()); + } + + @Override + public String toString() { + return "[pongMessage: " + pongMessage; + } + + @Override + public boolean valid() { + return NetUtil.validNode(getFrom()); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/DiscoverTask.java b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/DiscoverTask.java new file mode 100644 index 00000000000..823e4d4dd36 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/DiscoverTask.java @@ -0,0 +1,87 @@ +package org.tron.p2p.discover.protocol.kad; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.protocol.kad.table.KademliaOptions; +import org.tron.p2p.utils.NetUtil; + +@Slf4j(topic = "net") +public class DiscoverTask { + + private ScheduledExecutorService discoverer = Executors.newSingleThreadScheduledExecutor( + BasicThreadFactory.builder().namingPattern("discoverTask").build()); + + private KadService kadService; + + private int loopNum = 0; + private byte[] nodeId; + + public DiscoverTask(KadService kadService) { + this.kadService = kadService; + } + + public void init() { + discoverer.scheduleWithFixedDelay(() -> { + try { + loopNum++; + if (loopNum % KademliaOptions.MAX_LOOP_NUM == 0) { + loopNum = 0; + nodeId = kadService.getPublicHomeNode().getId(); + } else { + nodeId = NetUtil.getNodeId(); + } + discover(nodeId, 0, new ArrayList<>()); + } catch (Exception e) { + logger.error("DiscoverTask fails to be executed", e); + } + }, 1, KademliaOptions.DISCOVER_CYCLE, TimeUnit.MILLISECONDS); + logger.debug("DiscoverTask started"); + } + + private void discover(byte[] nodeId, int round, List prevTriedNodes) { + + List closest = kadService.getTable().getClosestNodes(nodeId); + List tried = new ArrayList<>(); + for (Node n : closest) { + if (!tried.contains(n) && !prevTriedNodes.contains(n)) { + try { + kadService.getNodeHandler(n).sendFindNode(nodeId); + tried.add(n); + } catch (Exception e) { + logger.error("Unexpected Exception occurred while sending FindNodeMessage", e); + } + } + + if (tried.size() == KademliaOptions.ALPHA) { + break; + } + } + + try { + Thread.sleep(KademliaOptions.WAIT_TIME); + } catch (InterruptedException e) { + logger.warn("Discover task interrupted"); + Thread.currentThread().interrupt(); + } + + if (tried.isEmpty()) { + return; + } + + if (++round == KademliaOptions.MAX_STEPS) { + return; + } + tried.addAll(prevTriedNodes); + discover(nodeId, round, tried); + } + + public void close() { + discoverer.shutdownNow(); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/KadService.java b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/KadService.java new file mode 100644 index 00000000000..cfdf30d1974 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/KadService.java @@ -0,0 +1,219 @@ +package org.tron.p2p.discover.protocol.kad; + +import java.net.Inet4Address; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.DiscoverService; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.kad.FindNodeMessage; +import org.tron.p2p.discover.message.kad.KadMessage; +import org.tron.p2p.discover.message.kad.NeighborsMessage; +import org.tron.p2p.discover.message.kad.PingMessage; +import org.tron.p2p.discover.message.kad.PongMessage; +import org.tron.p2p.discover.protocol.kad.table.NodeTable; +import org.tron.p2p.discover.socket.UdpEvent; + +@Slf4j(topic = "net") +public class KadService implements DiscoverService { + + private static final int MAX_NODES = 2000; + private static final int NODES_TRIM_THRESHOLD = 3000; + @Getter + @Setter + private static long pingTimeout = 15_000; + + private final List bootNodes = new ArrayList<>(); + + private volatile boolean inited = false; + + private final Map nodeHandlerMap = new ConcurrentHashMap<>(); + + private Consumer messageSender; + + private NodeTable table; + private Node homeNode; + + private ScheduledExecutorService pongTimer; + private DiscoverTask discoverTask; + + public void init() { + for (InetSocketAddress address : Parameter.p2pConfig.getSeedNodes()) { + bootNodes.add(new Node(address)); + } + for (InetSocketAddress address : Parameter.p2pConfig.getActiveNodes()) { + bootNodes.add(new Node(address)); + } + this.pongTimer = Executors.newSingleThreadScheduledExecutor( + BasicThreadFactory.builder().namingPattern("pongTimer").build()); + this.homeNode = new Node(Parameter.p2pConfig.getNodeID(), Parameter.p2pConfig.getIp(), + Parameter.p2pConfig.getIpv6(), Parameter.p2pConfig.getPort()); + this.table = new NodeTable(homeNode); + + if (Parameter.p2pConfig.isDiscoverEnable()) { + discoverTask = new DiscoverTask(this); + discoverTask.init(); + } + } + + public void close() { + try { + if (pongTimer != null) { + pongTimer.shutdownNow(); + } + + if (discoverTask != null) { + discoverTask.close(); + } + } catch (Exception e) { + logger.error("Close nodeManagerTasksTimer or pongTimer failed", e); + throw e; + } + } + + public List getConnectableNodes() { + return getAllNodes().stream() + .filter(node -> node.isConnectible(Parameter.p2pConfig.getNetworkId())) + .filter(node -> node.getPreferInetSocketAddress() != null) + .collect(Collectors.toList()); + } + + public List getTableNodes() { + return table.getTableNodes(); + } + + public List getAllNodes() { + List nodeList = new ArrayList<>(); + for (NodeHandler nodeHandler : nodeHandlerMap.values()) { + nodeList.add(nodeHandler.getNode()); + } + return nodeList; + } + + @Override + public void setMessageSender(Consumer messageSender) { + this.messageSender = messageSender; + } + + @Override + public void channelActivated() { + if (!inited) { + inited = true; + + for (Node node : bootNodes) { + getNodeHandler(node); + } + } + } + + @Override + public void handleEvent(UdpEvent udpEvent) { + KadMessage m = (KadMessage) udpEvent.getMessage(); + + InetSocketAddress sender = udpEvent.getAddress(); + + Node n; + if (sender.getAddress() instanceof Inet4Address) { + n = new Node(m.getFrom().getId(), sender.getHostString(), m.getFrom().getHostV6(), + sender.getPort(), m.getFrom().getPort()); + } else { + n = new Node(m.getFrom().getId(), m.getFrom().getHostV4(), sender.getHostString(), + sender.getPort(), m.getFrom().getPort()); + } + + NodeHandler nodeHandler = getNodeHandler(n); + nodeHandler.getNode().setId(n.getId()); + nodeHandler.getNode().touch(); + + switch (m.getType()) { + case KAD_PING: + nodeHandler.handlePing((PingMessage) m); + break; + case KAD_PONG: + nodeHandler.handlePong((PongMessage) m); + break; + case KAD_FIND_NODE: + nodeHandler.handleFindNode((FindNodeMessage) m); + break; + case KAD_NEIGHBORS: + nodeHandler.handleNeighbours((NeighborsMessage) m, sender); + break; + default: + break; + } + } + + public NodeHandler getNodeHandler(Node n) { + NodeHandler ret = null; + InetSocketAddress inet4 = n.getInetSocketAddressV4(); + InetSocketAddress inet6 = n.getInetSocketAddressV6(); + if (inet4 != null) { + ret = nodeHandlerMap.get(inet4); + } + if (ret == null && inet6 != null) { + ret = nodeHandlerMap.get(inet6); + } + + if (ret == null) { + trimTable(); + ret = new NodeHandler(n, this); + if (n.getPreferInetSocketAddress() != null) { + nodeHandlerMap.put(n.getPreferInetSocketAddress(), ret); + } + } else { + ret.getNode().updateHostV4(n.getHostV4()); + ret.getNode().updateHostV6(n.getHostV6()); + } + return ret; + } + + public NodeTable getTable() { + return table; + } + + public Node getPublicHomeNode() { + return homeNode; + } + + public void sendOutbound(UdpEvent udpEvent) { + if (Parameter.p2pConfig.isDiscoverEnable() && messageSender != null) { + messageSender.accept(udpEvent); + } + } + + public ScheduledExecutorService getPongTimer() { + return pongTimer; + } + + private void trimTable() { + if (nodeHandlerMap.size() > NODES_TRIM_THRESHOLD) { + nodeHandlerMap.values().forEach(handler -> { + if (!handler.getNode().isConnectible(Parameter.p2pConfig.getNetworkId())) { + nodeHandlerMap.values().remove(handler); + } + }); + } + if (nodeHandlerMap.size() > NODES_TRIM_THRESHOLD) { + List sorted = new ArrayList<>(nodeHandlerMap.values()); + sorted.sort(Comparator.comparingLong(o -> o.getNode().getUpdateTime())); + for (NodeHandler handler : sorted) { + nodeHandlerMap.values().remove(handler); + if (nodeHandlerMap.size() <= MAX_NODES) { + break; + } + } + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/NodeHandler.java b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/NodeHandler.java new file mode 100644 index 00000000000..e266a274f2e --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/NodeHandler.java @@ -0,0 +1,250 @@ +package org.tron.p2p.discover.protocol.kad; + +import java.net.InetSocketAddress; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.Message; +import org.tron.p2p.discover.message.kad.FindNodeMessage; +import org.tron.p2p.discover.message.kad.NeighborsMessage; +import org.tron.p2p.discover.message.kad.PingMessage; +import org.tron.p2p.discover.message.kad.PongMessage; +import org.tron.p2p.discover.socket.UdpEvent; + +@Slf4j(topic = "net") +public class NodeHandler { + + private Node node; + private volatile State state; + private KadService kadService; + private NodeHandler replaceCandidate; + private AtomicInteger pingTrials = new AtomicInteger(3); + private volatile boolean waitForPong = false; + private volatile boolean waitForNeighbors = false; + private volatile int findNodeFail; + private static int maxFindNodeFailures = 5; + + public NodeHandler(Node node, KadService kadService) { + this.node = node; + this.kadService = kadService; + // send ping only if IP stack is compatible + if (node.getPreferInetSocketAddress() != null) { + changeState(State.DISCOVERED); + } + } + + public Node getNode() { + return node; + } + + public void setNode(Node node) { + this.node = node; + } + + public State getState() { + return state; + } + + private void challengeWith(NodeHandler replaceCandidate) { + this.replaceCandidate = replaceCandidate; + changeState(State.EVICTCANDIDATE); + } + + // Manages state transfers + public void changeState(State newState) { + State oldState = state; + if (newState == State.DISCOVERED) { + sendPing(); + } + + if (newState == State.ALIVE) { + Node evictCandidate = kadService.getTable().addNode(this.node); + if (evictCandidate == null) { + newState = State.ACTIVE; + } else { + NodeHandler evictHandler = kadService.getNodeHandler(evictCandidate); + if (evictHandler.state != State.EVICTCANDIDATE) { + evictHandler.challengeWith(this); + } + } + } + if (newState == State.ACTIVE) { + if (oldState == State.ALIVE) { + // new node won the challenge + kadService.getTable().addNode(node); + } else if (oldState == State.EVICTCANDIDATE) { + // nothing to do here the node is already in the table + } else { + // wrong state transition + } + } + + if (newState == State.DEAD) { + if (oldState == State.EVICTCANDIDATE) { + // lost the challenge + // Removing ourselves from the table + kadService.getTable().dropNode(node); + // Congratulate the winner + replaceCandidate.changeState(State.ACTIVE); + } else if (oldState == State.ALIVE) { + // ok the old node was better, nothing to do here + } else { + // wrong state transition + } + } + + if (newState == State.EVICTCANDIDATE) { + // trying to survive, sending ping and waiting for pong + sendPing(); + } + state = newState; + } + + public void handlePing(PingMessage msg) { + if (!kadService.getTable().getNode().equals(node)) { + sendPong(); + } + node.setP2pVersion(msg.getNetworkId()); + if (!node.isConnectible(Parameter.p2pConfig.getNetworkId())) { + changeState(State.DEAD); + } else if (state.equals(State.DEAD)) { + changeState(State.DISCOVERED); + } + } + + public void handlePong(PongMessage msg) { + if (waitForPong) { + waitForPong = false; + node.setP2pVersion(msg.getNetworkId()); + if (!node.isConnectible(Parameter.p2pConfig.getNetworkId())) { + changeState(State.DEAD); + } else { + changeState(State.ALIVE); + } + } + } + + public void handleNeighbours(NeighborsMessage msg, InetSocketAddress sender) { + if (!waitForNeighbors) { + logger.warn("Receive neighbors from {} without send find nodes", sender); + return; + } + findNodeFail = 0; + waitForNeighbors = false; + for (Node n : msg.getNodes()) { + if (!kadService.getPublicHomeNode().getHexId().equals(n.getHexId())) { + kadService.getNodeHandler(n); + } + } + } + + public void handleFindNode(FindNodeMessage msg) { + List closest = kadService.getTable().getClosestNodes(msg.getTargetId()); + sendNeighbours(closest, msg.getTimestamp()); + } + + public void handleTimedOut() { + waitForPong = false; + if (pingTrials.getAndDecrement() > 0) { + sendPing(); + } else { + if (state == State.DISCOVERED || state == State.EVICTCANDIDATE) { + changeState(State.DEAD); + } else { + // TODO just influence to reputation + } + } + } + + public void sendPing() { + PingMessage msg = new PingMessage(kadService.getPublicHomeNode(), getNode()); + waitForPong = true; + sendMessage(msg); + + if (kadService.getPongTimer().isShutdown()) { + return; + } + kadService.getPongTimer().schedule(() -> { + try { + if (waitForPong) { + waitForPong = false; + handleTimedOut(); + } + } catch (Exception e) { + logger.error("Unhandled exception in pong timer schedule", e); + } + }, KadService.getPingTimeout(), TimeUnit.MILLISECONDS); + } + + public void sendPong() { + Message pong = new PongMessage(kadService.getPublicHomeNode()); + sendMessage(pong); + } + + public void sendFindNode(byte[] target) { + if (waitForNeighbors) { + findNodeFail++; + if (findNodeFail >= maxFindNodeFailures) { + if (kadService.getTable().failFindNode(node)) { + changeState(State.DEAD); + return; + } + } + } + waitForNeighbors = true; + FindNodeMessage msg = new FindNodeMessage(kadService.getPublicHomeNode(), target); + sendMessage(msg); + } + + public void sendNeighbours(List neighbours, long sequence) { + Message msg = new NeighborsMessage(kadService.getPublicHomeNode(), neighbours, sequence); + sendMessage(msg); + } + + private void sendMessage(Message msg) { + kadService.sendOutbound(new UdpEvent(msg, node.getPreferInetSocketAddress())); + } + + @Override + public String toString() { + return "NodeHandler[state: " + state + ", node: " + node.getHostKey() + ":" + node.getPort() + + "]"; + } + + public enum State { + /** + * The new node was just discovered either by receiving it with Neighbours message or by + * receiving Ping from a new node In either case we are sending Ping and waiting for Pong If the + * Pong is received the node becomes {@link #ALIVE} If the Pong was timed out the node becomes + * {@link #DEAD} + */ + DISCOVERED, + /** + * The node didn't send the Pong message back withing acceptable timeout This is the final + * state + */ + DEAD, + /** + * The node responded with Pong and is now the candidate for inclusion to the table If the table + * has bucket space for this node it is added to table and becomes {@link #ACTIVE} If the table + * bucket is full this node is challenging with the old node from the bucket if it wins then old + * node is dropped, and this node is added and becomes {@link #ACTIVE} else this node becomes + * {@link #DEAD} + */ + ALIVE, + /** + * The node is included in the table. It may become {@link #EVICTCANDIDATE} if a new node wants + * to become Active but the table bucket is full. + */ + ACTIVE, + /** + * This node is in the table but is currently challenging with a new Node candidate to survive + * in the table bucket If it wins then returns back to {@link #ACTIVE} state, else is evicted + * from the table and becomes {@link #DEAD} + */ + EVICTCANDIDATE + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/DistanceComparator.java b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/DistanceComparator.java new file mode 100644 index 00000000000..30da3b0fdab --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/DistanceComparator.java @@ -0,0 +1,26 @@ +package org.tron.p2p.discover.protocol.kad.table; + +import java.util.Comparator; +import org.tron.p2p.discover.Node; + +public class DistanceComparator implements Comparator { + private byte[] targetId; + + DistanceComparator(byte[] targetId) { + this.targetId = targetId; + } + + @Override + public int compare(Node e1, Node e2) { + int d1 = NodeEntry.distance(targetId, e1.getId()); + int d2 = NodeEntry.distance(targetId, e2.getId()); + + if (d1 > d2) { + return 1; + } else if (d1 < d2) { + return -1; + } else { + return 0; + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/KademliaOptions.java b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/KademliaOptions.java new file mode 100644 index 00000000000..b1362438af0 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/KademliaOptions.java @@ -0,0 +1,12 @@ +package org.tron.p2p.discover.protocol.kad.table; + +public class KademliaOptions { + public static final int BUCKET_SIZE = 16; + public static final int ALPHA = 3; + public static final int BINS = 17; + public static final int MAX_STEPS = 8; + public static final int MAX_LOOP_NUM = 5; + + public static final long DISCOVER_CYCLE = 7200; //discovery cycle interval in millis + public static final long WAIT_TIME = 100; //wait time in millis +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/NodeBucket.java b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/NodeBucket.java new file mode 100644 index 00000000000..a79ade07986 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/NodeBucket.java @@ -0,0 +1,53 @@ +package org.tron.p2p.discover.protocol.kad.table; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class NodeBucket { + private final int depth; + private List nodes = new ArrayList<>(); + + NodeBucket(int depth) { + this.depth = depth; + } + + public int getDepth() { + return depth; + } + + public synchronized NodeEntry addNode(NodeEntry e) { + if (!nodes.contains(e)) { + if (nodes.size() >= KademliaOptions.BUCKET_SIZE) { + return getLastSeen(); + } else { + nodes.add(e); + } + } + + return null; + } + + private NodeEntry getLastSeen() { + List sorted = nodes; + Collections.sort(sorted, new TimeComparator()); + return sorted.get(0); + } + + public synchronized void dropNode(NodeEntry entry) { + for (NodeEntry e : nodes) { + if (e.getId().equals(entry.getId())) { + nodes.remove(e); + break; + } + } + } + + public int getNodesCount() { + return nodes.size(); + } + + public List getNodes() { + return nodes; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/NodeEntry.java b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/NodeEntry.java new file mode 100644 index 00000000000..dc14a7fbd53 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/NodeEntry.java @@ -0,0 +1,88 @@ +package org.tron.p2p.discover.protocol.kad.table; + +import org.tron.p2p.discover.Node; + +public class NodeEntry { + private Node node; + private String entryId; + private int distance; + private long modified; + + public NodeEntry(byte[] ownerId, Node n) { + this.node = n; + entryId = n.getHostKey(); + distance = distance(ownerId, n.getId()); + touch(); + } + + public static int distance(byte[] ownerId, byte[] targetId) { + byte[] h1 = targetId; + byte[] h2 = ownerId; + + byte[] hash = new byte[StrictMath.min(h1.length, h2.length)]; + + for (int i = 0; i < hash.length; i++) { + hash[i] = (byte) (h1[i] ^ h2[i]); + } + + int d = KademliaOptions.BINS; + + for (byte b : hash) { + if (b == 0) { + d -= 8; + } else { + int count = 0; + for (int i = 7; i >= 0; i--) { + boolean a = ((b & 0xff) & (1 << i)) == 0; + if (a) { + count++; + } else { + break; + } + } + + d -= count; + + break; + } + } + return d; + } + + public void touch() { + modified = System.currentTimeMillis(); + } + + public int getDistance() { + return distance; + } + + public String getId() { + return entryId; + } + + public Node getNode() { + return node; + } + + public long getModified() { + return modified; + } + + @Override + public boolean equals(Object o) { + boolean ret = false; + + if (o != null && this.getClass() == o.getClass()) { + NodeEntry e = (NodeEntry) o; + ret = this.getId().equals(e.getId()); + } + + return ret; + } + + @Override + public int hashCode() { + return this.entryId.hashCode(); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/NodeTable.java b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/NodeTable.java new file mode 100644 index 00000000000..110130573ac --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/NodeTable.java @@ -0,0 +1,129 @@ +package org.tron.p2p.discover.protocol.kad.table; + +import static org.tron.p2p.discover.protocol.kad.table.KademliaOptions.BUCKET_SIZE; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.tron.p2p.discover.Node; + +public class NodeTable { + private final Node node; // our node + private transient NodeBucket[] buckets; + private transient Map nodes; + + public NodeTable(Node n) { + this.node = n; + initialize(); + } + + public Node getNode() { + return node; + } + + public final void initialize() { + nodes = new HashMap<>(); + buckets = new NodeBucket[KademliaOptions.BINS]; + for (int i = 0; i < KademliaOptions.BINS; i++) { + buckets[i] = new NodeBucket(i); + } + } + + public synchronized Node addNode(Node n) { + if (n.getHostKey().equals(node.getHostKey())) { + return null; + } + + NodeEntry entry = nodes.get(n.getHostKey()); + if (entry != null) { + entry.touch(); + return null; + } + + NodeEntry e = new NodeEntry(node.getId(), n); + NodeEntry lastSeen = buckets[getBucketId(e)].addNode(e); + if (lastSeen != null) { + return lastSeen.getNode(); + } + nodes.put(n.getHostKey(), e); + return null; + } + + public synchronized void dropNode(Node n) { + NodeEntry entry = nodes.get(n.getHostKey()); + if (entry != null) { + nodes.remove(n.getHostKey()); + buckets[getBucketId(entry)].dropNode(entry); + } + } + + public synchronized boolean contains(Node n) { + return nodes.containsKey(n.getHostKey()); + } + + public synchronized void touchNode(Node n) { + NodeEntry entry = nodes.get(n.getHostKey()); + if (entry != null) { + entry.touch(); + } + } + + public int getBucketsCount() { + int i = 0; + for (NodeBucket b : buckets) { + if (b.getNodesCount() > 0) { + i++; + } + } + return i; + } + + public int getBucketId(NodeEntry e) { + int id = e.getDistance() - 1; + return StrictMath.max(id, 0); + } + + public synchronized int getNodesCount() { + return nodes.size(); + } + + public synchronized List getAllNodes() { + return new ArrayList<>(nodes.values()); + } + + public synchronized boolean failFindNode(Node n) { + NodeEntry entry = nodes.get(n.getHostKey()); + if (entry == null) { + return false; + } + if (buckets[getBucketId(entry)].getNodes().size() >= BUCKET_SIZE / 4) { + nodes.remove(n.getHostKey()); + buckets[getBucketId(entry)].dropNode(entry); + return true; + } + return false; + } + + public synchronized List getClosestNodes(byte[] targetId) { + List closestEntries = getAllNodes(); + List closestNodes = new ArrayList<>(); + for (NodeEntry e : closestEntries) { + closestNodes.add((Node) e.getNode().clone()); + } + Collections.sort(closestNodes, new DistanceComparator(targetId)); + if (closestNodes.size() > BUCKET_SIZE) { + closestNodes = closestNodes.subList(0, BUCKET_SIZE); + } + return closestNodes; + } + + public synchronized List getTableNodes() { + List nodeList = new ArrayList<>(); + for (NodeEntry nodeEntry : nodes.values()) { + nodeList.add(nodeEntry.getNode()); + } + return nodeList; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/TimeComparator.java b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/TimeComparator.java new file mode 100644 index 00000000000..7e2e94186e0 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/protocol/kad/table/TimeComparator.java @@ -0,0 +1,19 @@ +package org.tron.p2p.discover.protocol.kad.table; + +import java.util.Comparator; + +public class TimeComparator implements Comparator { + @Override + public int compare(NodeEntry e1, NodeEntry e2) { + long t1 = e1.getModified(); + long t2 = e2.getModified(); + + if (t1 < t2) { + return 1; + } else if (t1 > t2) { + return -1; + } else { + return 0; + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/socket/DiscoverServer.java b/p2p/src/main/java/org/tron/p2p/discover/socket/DiscoverServer.java new file mode 100644 index 00000000000..4840d42a7e2 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/socket/DiscoverServer.java @@ -0,0 +1,93 @@ +package org.tron.p2p.discover.socket; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioDatagramChannel; +import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; +import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.stats.TrafficStats; + +@Slf4j(topic = "net") +public class DiscoverServer { + + private Channel channel; + private EventHandler eventHandler; + + private final int SERVER_RESTART_WAIT = 5000; + private final int SERVER_CLOSE_WAIT = 10; + private final int port = Parameter.p2pConfig.getPort(); + private volatile boolean shutdown = false; + + public void init(EventHandler eventHandler) { + this.eventHandler = eventHandler; + new Thread(() -> { + try { + start(); + } catch (Exception e) { + logger.error("Discovery server start failed", e); + } + }, "DiscoverServer").start(); + } + + public void close() { + logger.info("Closing discovery server..."); + shutdown = true; + if (channel != null) { + try { + channel.close().await(SERVER_CLOSE_WAIT, TimeUnit.SECONDS); + } catch (Exception e) { + logger.error("Closing discovery server failed", e); + } + } + } + + private void start() throws Exception { + NioEventLoopGroup group = new NioEventLoopGroup(Parameter.UDP_NETTY_WORK_THREAD_NUM, + new BasicThreadFactory.Builder().namingPattern("discoverServer").build()); + try { + while (!shutdown) { + Bootstrap b = new Bootstrap(); + b.group(group) + .channel(NioDatagramChannel.class) + .handler(new ChannelInitializer() { + @Override + public void initChannel(NioDatagramChannel ch) + throws Exception { + ch.pipeline().addLast(TrafficStats.udp); + ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender()); + ch.pipeline().addLast(new ProtobufVarint32FrameDecoder()); + ch.pipeline().addLast(new P2pPacketDecoder()); + MessageHandler messageHandler = new MessageHandler(ch, eventHandler); + eventHandler.setMessageSender(messageHandler); + ch.pipeline().addLast(messageHandler); + } + }); + + channel = b.bind(port).sync().channel(); + + logger.info("Discovery server started, bind port {}", port); + + channel.closeFuture().sync(); + if (shutdown) { + logger.info("Shutdown discovery server"); + break; + } + logger.warn("Restart discovery server after 5 sec pause..."); + Thread.sleep(SERVER_RESTART_WAIT); + } + } catch (InterruptedException e) { + logger.warn("Discover server interrupted"); + Thread.currentThread().interrupt(); + } catch (Exception e) { + logger.error("Start discovery server with port {} failed", port, e); + } finally { + group.shutdownGracefully().sync(); + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/socket/EventHandler.java b/p2p/src/main/java/org/tron/p2p/discover/socket/EventHandler.java new file mode 100644 index 00000000000..a8223fd5d59 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/socket/EventHandler.java @@ -0,0 +1,12 @@ +package org.tron.p2p.discover.socket; + +import java.util.function.Consumer; + +public interface EventHandler { + + void channelActivated(); + + void handleEvent(UdpEvent event); + + void setMessageSender(Consumer messageSender); +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/socket/MessageHandler.java b/p2p/src/main/java/org/tron/p2p/discover/socket/MessageHandler.java new file mode 100644 index 00000000000..8ee14d1692c --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/socket/MessageHandler.java @@ -0,0 +1,67 @@ +package org.tron.p2p.discover.socket; + +import io.netty.buffer.Unpooled; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.channel.socket.DatagramPacket; +import io.netty.channel.socket.nio.NioDatagramChannel; +import java.net.InetSocketAddress; +import java.util.function.Consumer; +import lombok.extern.slf4j.Slf4j; + +@Slf4j(topic = "net") +public class MessageHandler extends SimpleChannelInboundHandler + implements Consumer { + + private Channel channel; + + private EventHandler eventHandler; + + public MessageHandler(NioDatagramChannel channel, EventHandler eventHandler) { + this.channel = channel; + this.eventHandler = eventHandler; + } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + eventHandler.channelActivated(); + } + + @Override + public void channelRead0(ChannelHandlerContext ctx, UdpEvent udpEvent) { + logger.debug("Rcv udp msg type {}, len {} from {} ", + udpEvent.getMessage().getType(), + udpEvent.getMessage().getSendData().length, + udpEvent.getAddress()); + eventHandler.handleEvent(udpEvent); + } + + @Override + public void accept(UdpEvent udpEvent) { + logger.debug("Send udp msg type {}, len {} to {} ", + udpEvent.getMessage().getType(), + udpEvent.getMessage().getSendData().length, + udpEvent.getAddress()); + InetSocketAddress address = udpEvent.getAddress(); + sendPacket(udpEvent.getMessage().getSendData(), address); + } + + void sendPacket(byte[] wire, InetSocketAddress address) { + DatagramPacket packet = new DatagramPacket(Unpooled.copiedBuffer(wire), address); + channel.write(packet); + channel.flush(); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + ctx.flush(); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + logger.warn("Exception caught in udp message handler, {} {}", + ctx.channel().remoteAddress(), cause.getMessage()); + ctx.close(); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/socket/P2pPacketDecoder.java b/p2p/src/main/java/org/tron/p2p/discover/socket/P2pPacketDecoder.java new file mode 100644 index 00000000000..010815307b7 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/socket/P2pPacketDecoder.java @@ -0,0 +1,51 @@ +package org.tron.p2p.discover.socket; + +import com.google.protobuf.InvalidProtocolBufferException; +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.socket.DatagramPacket; +import io.netty.handler.codec.MessageToMessageDecoder; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.discover.message.Message; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.utils.ByteArray; + +@Slf4j(topic = "net") +public class P2pPacketDecoder extends MessageToMessageDecoder { + + private static final int MAXSIZE = 2048; + + @Override + public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List out) + throws Exception { + ByteBuf buf = packet.content(); + int length = buf.readableBytes(); + if (length <= 1 || length >= MAXSIZE) { + logger.warn("UDP rcv bad packet, from {} length = {}", ctx.channel().remoteAddress(), length); + return; + } + byte[] encoded = new byte[length]; + buf.readBytes(encoded); + try { + UdpEvent event = new UdpEvent(Message.parse(encoded), packet.sender()); + out.add(event); + } catch (P2pException pe) { + if (pe.getType().equals(P2pException.TypeEnum.BAD_MESSAGE)) { + logger.error("Message validation failed, type {}, len {}, address {}", encoded[0], + encoded.length, packet.sender()); + } else { + logger.info("Parse msg failed, type {}, len {}, address {}", encoded[0], encoded.length, + packet.sender()); + } + } catch (InvalidProtocolBufferException e) { + logger.warn("An exception occurred while parsing the message, type {}, len {}, address {}, " + + "data {}, cause: {}", encoded[0], encoded.length, packet.sender(), + ByteArray.toHexString(encoded), e.getMessage()); + } catch (Exception e) { + logger.error("An exception occurred while parsing the message, type {}, len {}, address {}, " + + "data {}", encoded[0], encoded.length, packet.sender(), + ByteArray.toHexString(encoded), e); + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/discover/socket/UdpEvent.java b/p2p/src/main/java/org/tron/p2p/discover/socket/UdpEvent.java new file mode 100644 index 00000000000..244d1c0b44f --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/discover/socket/UdpEvent.java @@ -0,0 +1,32 @@ +package org.tron.p2p.discover.socket; + +import java.net.InetSocketAddress; +import org.tron.p2p.discover.message.Message; + +public class UdpEvent { + private Message message; + //when receive UdpEvent, this is sender address + //when send UdpEvent, this is target address + private InetSocketAddress address; + + public UdpEvent(Message message, InetSocketAddress address) { + this.message = message; + this.address = address; + } + + public Message getMessage() { + return message; + } + + public void setMessage(Message message) { + this.message = message; + } + + public InetSocketAddress getAddress() { + return address; + } + + public void setAddress(InetSocketAddress address) { + this.address = address; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/DnsManager.java b/p2p/src/main/java/org/tron/p2p/dns/DnsManager.java new file mode 100644 index 00000000000..4deb700fbc0 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/DnsManager.java @@ -0,0 +1,79 @@ +package org.tron.p2p.dns; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.discover.Node; +import org.tron.p2p.dns.sync.Client; +import org.tron.p2p.dns.sync.RandomIterator; +import org.tron.p2p.dns.tree.Tree; +import org.tron.p2p.dns.update.PublishService; +import org.tron.p2p.utils.NetUtil; + +@Slf4j(topic = "net") +public class DnsManager { + + private static PublishService publishService; + private static Client syncClient; + private static RandomIterator randomIterator; + private static Set localIpSet; + + public static void init() { + publishService = new PublishService(); + syncClient = new Client(); + publishService.init(); + syncClient.init(); + randomIterator = syncClient.newIterator(); + localIpSet = NetUtil.getAllLocalAddress(); + } + + public static void close() { + if (publishService != null) { + publishService.close(); + } + if (syncClient != null) { + syncClient.close(); + } + if (randomIterator != null) { + randomIterator.close(); + } + } + + public static List getDnsNodes() { + Set nodes = new HashSet<>(); + for (Map.Entry entry : syncClient.getTrees().entrySet()) { + Tree tree = entry.getValue(); + int v4Size = 0; + int v6Size = 0; + List dnsNodes = tree.getDnsNodes(); + List ipv6Nodes = new ArrayList<>(); + for (DnsNode dnsNode : dnsNodes) { + //logger.debug("DnsNode:{}", dnsNode); + if (dnsNode.getInetSocketAddressV4() != null) { + v4Size += 1; + } + if (dnsNode.getInetSocketAddressV6() != null) { + v6Size += 1; + ipv6Nodes.add(dnsNode); + } + } + List connectAbleNodes = dnsNodes.stream() + .filter(node -> node.getPreferInetSocketAddress() != null) + .filter(node -> !localIpSet.contains( + node.getPreferInetSocketAddress().getAddress().getHostAddress())) + .collect(Collectors.toList()); + logger.debug("Tree {} node size:{}, v4 node size:{}, v6 node size:{}, connectable size:{}", + entry.getKey(), dnsNodes.size(), v4Size, v6Size, connectAbleNodes.size()); + nodes.addAll(connectAbleNodes); + } + return new ArrayList<>(nodes); + } + + public static Node getRandomNodes() { + return randomIterator.next(); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/DnsNode.java b/p2p/src/main/java/org/tron/p2p/dns/DnsNode.java new file mode 100644 index 00000000000..9044b12f0d3 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/DnsNode.java @@ -0,0 +1,95 @@ +package org.tron.p2p.dns; + +import static org.tron.p2p.discover.message.kad.KadMessage.getEndpointFromNode; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.tron.p2p.base.Constant; +import org.tron.p2p.discover.Node; +import org.tron.p2p.dns.tree.Algorithm; +import org.tron.p2p.protos.Discover; +import org.tron.p2p.protos.Discover.EndPoints; +import org.tron.p2p.protos.Discover.EndPoints.Builder; +import org.tron.p2p.protos.Discover.Endpoint; +import org.tron.p2p.utils.ByteArray; + +@Slf4j(topic = "net") +public class DnsNode extends Node implements Comparable { + + private static final long serialVersionUID = 6689513341024130226L; + private String v4Hex = Constant.ipV4Hex; + private String v6Hex = Constant.ipV6Hex; + + public DnsNode(byte[] id, String hostV4, String hostV6, int port) throws UnknownHostException { + super(null, hostV4, hostV6, port); + if (StringUtils.isNotEmpty(hostV4)) { + this.v4Hex = ipToString(hostV4); + } + if (StringUtils.isNotEmpty(hostV6)) { + this.v6Hex = ipToString(hostV6); + } + } + + public static String compress(List nodes) { + Builder builder = Discover.EndPoints.newBuilder(); + nodes.forEach(node -> { + Endpoint endpoint = getEndpointFromNode(node); + builder.addNodes(endpoint); + }); + return Algorithm.encode64(builder.build().toByteArray()); + } + + public static List decompress(String base64Content) + throws InvalidProtocolBufferException, UnknownHostException { + byte[] data = Algorithm.decode64(base64Content); + EndPoints endPoints = EndPoints.parseFrom(data); + + List dnsNodes = new ArrayList<>(); + for (Endpoint endpoint : endPoints.getNodesList()) { + DnsNode dnsNode = new DnsNode(endpoint.getNodeId().toByteArray(), + new String(endpoint.getAddress().toByteArray()), + new String(endpoint.getAddressIpv6().toByteArray()), + endpoint.getPort()); + dnsNodes.add(dnsNode); + } + return dnsNodes; + } + + public String ipToString(String ip) throws UnknownHostException { + byte[] bytes = InetAddress.getByName(ip).getAddress(); + return ByteArray.toHexString(bytes); + } + + public int getNetworkA() { + if (StringUtils.isNotEmpty(hostV4)) { + return Integer.parseInt(hostV4.split("\\.")[0]); + } else { + return 0; + } + } + + @Override + public int compareTo(DnsNode o) { + if (this.v4Hex.compareTo(o.v4Hex) != 0) { + return this.v4Hex.compareTo(o.v4Hex); + } else if (this.v6Hex.compareTo(o.v6Hex) != 0) { + return this.v6Hex.compareTo(o.v6Hex); + } else { + return this.port - o.port; + } + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof DnsNode)) { + return false; + } + DnsNode other = (DnsNode) o; + return v4Hex.equals(other.v4Hex) && v6Hex.equals(other.v6Hex) && port == other.port; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/lookup/LookUpTxt.java b/p2p/src/main/java/org/tron/p2p/dns/lookup/LookUpTxt.java new file mode 100644 index 00000000000..effb5f5217e --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/lookup/LookUpTxt.java @@ -0,0 +1,204 @@ +package org.tron.p2p.dns.lookup; + +import com.google.common.annotations.VisibleForTesting; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.time.Duration; +import java.util.Random; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.tron.p2p.base.Parameter; +import org.xbill.DNS.AAAARecord; +import org.xbill.DNS.ARecord; +import org.xbill.DNS.Lookup; +import org.xbill.DNS.Record; +import org.xbill.DNS.SimpleResolver; +import org.xbill.DNS.TXTRecord; +import org.xbill.DNS.TextParseException; +import org.xbill.DNS.Type; + +@Slf4j(topic = "net") +public class LookUpTxt { + + static String[] publicDnsV4 = new String[] { + "114.114.114.114", "114.114.115.115", //114 DNS + "223.5.5.5", "223.6.6.6", //AliDNS + //"180.76.76.76", //BaiduDNS slow + "119.29.29.29", //DNSPod DNS+ + // "182.254.116.116", //DNSPod DNS+ slow + //"1.2.4.8", "210.2.4.8", //CNNIC SDNS + "117.50.11.11", "117.50.22.22", //oneDNS + "101.226.4.6", "218.30.118.6", "123.125.81.6", "140.207.198.6", //DNS pai + "8.8.8.8", "8.8.4.4", //Google DNS + "9.9.9.9", //IBM Quad9 + //"208.67.222.222", "208.67.220.220", //OpenDNS slow + //"199.91.73.222", "178.79.131.110" //V2EX DNS + }; + + static String[] publicDnsV6 = new String[] { + "2606:4700:4700::1111", "2606:4700:4700::1001", //Cloudflare + "2400:3200::1", "2400:3200:baba::1", //AliDNS + //"2400:da00::6666", //BaiduDNS + "2a00:5a60::ad1:0ff", "2a00:5a60::ad2:0ff", //AdGuard + "2620:74:1b::1:1", "2620:74:1c::2:2", //Verisign + //"2a05:dfc7:5::53", "2a05:dfc7:5::5353", //OpenNIC + "2a02:6b8::feed:0ff", "2a02:6b8:0:1::feed:0ff", //Yandex + "2001:4860:4860::8888", "2001:4860:4860::8844", //Google DNS + "2620:fe::fe", "2620:fe::9", //IBM Quad9 + //"2620:119:35::35", "2620:119:53::53", //OpenDNS + "2a00:5a60::ad1:0ff", "2a00:5a60::ad2:0ff" //AdGuard + }; + + @VisibleForTesting + static int maxRetryTimes = 5; + static Random random = new Random(); + static final ExecutorService OS_RESOLVER_EXECUTOR = new ThreadPoolExecutor( + 1, 8, 60L, TimeUnit.SECONDS, + new LinkedBlockingQueue<>(16), + r -> { + Thread t = new Thread(r, "dns-os-resolver"); + t.setDaemon(true); + return t; + }, + new ThreadPoolExecutor.AbortPolicy() + ); + + public static TXTRecord lookUpTxt(String hash, String domain) + throws TextParseException, UnknownHostException { + return lookUpTxt(hash + "." + domain); + } + + // only get first Record. + // as dns server has dns cache, we may get the name's latest TXTRecord ttl later after it changes + public static TXTRecord lookUpTxt(String name) throws TextParseException, UnknownHostException { + TXTRecord txt = null; + logger.info("LookUp name: {}", name); + Lookup lookup = new Lookup(name, Type.TXT); + int times = 0; + Record[] records = null; + long start = System.currentTimeMillis(); + while (times < maxRetryTimes) { + String publicDns; + if (StringUtils.isNotEmpty(Parameter.p2pConfig.getIp())) { + publicDns = publicDnsV4[random.nextInt(publicDnsV4.length)]; + } else { + publicDns = publicDnsV6[random.nextInt(publicDnsV6.length)]; + } + SimpleResolver simpleResolver = new SimpleResolver(InetAddress.getByName(publicDns)); + simpleResolver.setTimeout(Duration.ofMillis(1000)); + lookup.setResolver(simpleResolver); + long thisTime = System.currentTimeMillis(); + records = lookup.run(); + long end = System.currentTimeMillis(); + times += 1; + if (records != null) { + logger.debug("Succeed to use dns: {}, cur cost: {}ms, total cost: {}ms", publicDns, + end - thisTime, end - start); + break; + } else { + logger.debug("Failed to use dns: {}, cur cost: {}ms", publicDns, end - thisTime); + } + } + if (records == null) { + logger.error("Failed to lookUp name:{}", name); + return null; + } + for (Record item : records) { + txt = (TXTRecord) item; + } + return txt; + } + + /** + * Resolves a domain name to an IP address. Resolution order: + *
  • OS name resolver ({@link InetAddress}) — reads {@code /etc/hosts} first, + * so LAN IP mappings configured there are returned immediately without a DNS query.
  • + *
  • Random public DNS server (fallback, retried up to {@link #maxRetryTimes} times).
  • + * + * @param domain the domain name to resolve (e.g. {@code "nodes.example.com"}) + * @param useIPv4 {@code true} to query A records (IPv4); {@code false} to query AAAA + * records (IPv6) + * @return the resolved {@link InetAddress}, or {@code null} if resolution fails + */ + public static InetAddress lookUpIp(String domain, boolean useIPv4) { + if (StringUtils.isEmpty(domain)) { + return null; + } + logger.debug("LookUp {} for domain: {}", useIPv4 ? "IPv4" : "IPv6", domain); + + // Step 1: OS name resolver — honours /etc/hosts, so LAN mappings work without a DNS query. + Future future = OS_RESOLVER_EXECUTOR.submit( + () -> InetAddress.getAllByName(domain)); + try { + for (InetAddress addr : future.get(2000, TimeUnit.MILLISECONDS)) { + if ((useIPv4 && addr instanceof Inet4Address) + || (!useIPv4 && addr instanceof Inet6Address)) { + logger.debug("Resolved {} via OS name resolver (may be /etc/hosts): {}", domain, + addr.getHostAddress()); + return addr; + } + } + } catch (TimeoutException e) { + // cancel(true) sends an interrupt, but InetAddress.getAllByName() is a + // native blocking call and does NOT respond to interrupts. The thread + // will keep running until the OS-level resolution completes or times out. + // This is an accepted limitation of wrapping non-interruptible I/O in a Future. + future.cancel(true); + logger.debug("OS name resolver timed out for {}", domain); + } catch (ExecutionException e) { + logger.debug("OS name resolver failed for {}: {}", domain, e.getCause().getMessage()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // restore interrupt flag + logger.debug("OS name resolver interrupted for {}", domain); + } + + // Step 2: fall back to random public DNS servers. + int recordType = useIPv4 ? Type.A : Type.AAAA; + String[] publicDns = useIPv4 ? publicDnsV4 : publicDnsV6; + long start = System.currentTimeMillis(); + for (int times = 0; times < maxRetryTimes; times++) { + String dns = publicDns[random.nextInt(publicDns.length)]; + try { + Lookup lookup = new Lookup(domain, recordType); + SimpleResolver simpleResolver = new SimpleResolver(InetAddress.getByName(dns)); + simpleResolver.setTimeout(Duration.ofMillis(1000)); + lookup.setResolver(simpleResolver); + long thisTime = System.currentTimeMillis(); + Record[] records = lookup.run(); + long end = System.currentTimeMillis(); + if (records != null && records.length > 0) { + InetAddress address = useIPv4 + ? ((ARecord) records[0]).getAddress() + : ((AAAARecord) records[0]).getAddress(); + logger.debug("Resolved {} via public DNS {}, cur cost: {}ms, total cost: {}ms", + domain, dns, end - thisTime, end - start); + return address; + } + logger.debug("Public DNS {} failed for {}, cur cost: {}ms", dns, domain, + System.currentTimeMillis() - thisTime); + } catch (TextParseException | UnknownHostException e) { + logger.debug("Public DNS {} error for {}: {}", dns, domain, e.getMessage()); + } + } + + logger.warn("Failed to resolve {} for domain: {}", useIPv4 ? "IPv4" : "IPv6", domain); + return null; + } + + public static String joinTXTRecord(TXTRecord txtRecord) { + StringBuilder sb = new StringBuilder(); + for (String s : txtRecord.getStrings()) { + sb.append(s.trim()); + } + return sb.toString(); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/sync/Client.java b/p2p/src/main/java/org/tron/p2p/dns/sync/Client.java new file mode 100644 index 00000000000..097993da296 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/sync/Client.java @@ -0,0 +1,188 @@ +package org.tron.p2p.dns.sync; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import java.net.UnknownHostException; +import java.security.SignatureException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.dns.lookup.LookUpTxt; +import org.tron.p2p.dns.tree.Algorithm; +import org.tron.p2p.dns.tree.BranchEntry; +import org.tron.p2p.dns.tree.Entry; +import org.tron.p2p.dns.tree.LinkEntry; +import org.tron.p2p.dns.tree.NodesEntry; +import org.tron.p2p.dns.tree.RootEntry; +import org.tron.p2p.dns.tree.Tree; +import org.tron.p2p.exception.DnsException; +import org.tron.p2p.exception.DnsException.TypeEnum; +import org.tron.p2p.utils.ByteArray; +import org.xbill.DNS.TXTRecord; +import org.xbill.DNS.TextParseException; + +@Slf4j(topic = "net") +public class Client { + + public static final int recheckInterval = 60 * 60; //seconds, should be smaller than rootTTL + public static final int cacheLimit = 2000; + public static final int randomRetryTimes = 10; + private Cache cache; + @Getter + private final Map trees = new ConcurrentHashMap<>(); + private final Map clientTrees = new HashMap<>(); + + private final ScheduledExecutorService syncer = Executors.newSingleThreadScheduledExecutor( + BasicThreadFactory.builder().namingPattern("dnsSyncer").build()); + + public Client() { + this.cache = CacheBuilder.newBuilder() + .maximumSize(cacheLimit) + .recordStats() + .build(); + } + + public void init() { + if (!Parameter.p2pConfig.getTreeUrls().isEmpty()) { + syncer.scheduleWithFixedDelay(this::startSync, 5, recheckInterval, + TimeUnit.SECONDS); + } + } + + public void startSync() { + for (String urlScheme : Parameter.p2pConfig.getTreeUrls()) { + ClientTree clientTree = clientTrees.getOrDefault(urlScheme, new ClientTree(this)); + Tree tree = trees.getOrDefault(urlScheme, new Tree()); + trees.put(urlScheme, tree); + clientTrees.put(urlScheme, clientTree); + try { + syncTree(urlScheme, clientTree, tree); + } catch (Exception e) { + logger.error("SyncTree failed, url:" + urlScheme, e); + continue; + } + } + } + + public void syncTree(String urlScheme, ClientTree clientTree, Tree tree) throws Exception { + LinkEntry loc = LinkEntry.parseEntry(urlScheme); + if (clientTree == null) { + clientTree = new ClientTree(this); + } + if (clientTree.getLinkEntry() == null) { + clientTree.setLinkEntry(loc); + } + if (tree.getEntries().isEmpty()) { + // when sync tree first time, we can get the entries dynamically + clientTree.syncAll(tree.getEntries()); + } else { + Map tmpEntries = new HashMap<>(); + boolean[] isRootUpdate = clientTree.syncAll(tmpEntries); + if (!isRootUpdate[0]) { + tmpEntries.putAll(tree.getLinksMap()); + } + if (!isRootUpdate[1]) { + tmpEntries.putAll(tree.getNodesMap()); + } + // we update the entries after sync finishes, ignore branch difference + tree.setEntries(tmpEntries); + } + + tree.setRootEntry(clientTree.getRoot()); + logger.info("SyncTree {} complete, LinkEntry size:{}, NodesEntry size:{}, node size:{}", + urlScheme, tree.getLinksEntry().size(), tree.getNodesEntry().size(), + tree.getDnsNodes().size()); + } + + public RootEntry resolveRoot(LinkEntry linkEntry) throws TextParseException, DnsException, + SignatureException, UnknownHostException { + //do not put root in cache + TXTRecord txtRecord = LookUpTxt.lookUpTxt(linkEntry.getDomain()); + if (txtRecord == null) { + throw new DnsException(TypeEnum.LOOK_UP_ROOT_FAILED, "domain: " + linkEntry.getDomain()); + } + for (String txt : txtRecord.getStrings()) { + if (txt.startsWith(Entry.rootPrefix)) { + return RootEntry.parseEntry(txt, linkEntry.getUnCompressHexPublicKey(), + linkEntry.getDomain()); + } + } + throw new DnsException(TypeEnum.NO_ROOT_FOUND, "domain: " + linkEntry.getDomain()); + } + + // resolveEntry retrieves an entry from the cache or fetches it from the network + // if it isn't cached. + public Entry resolveEntry(String domain, String hash) + throws DnsException, TextParseException, UnknownHostException { + Entry entry = cache.getIfPresent(hash); + if (entry != null) { + return entry; + } + entry = doResolveEntry(domain, hash); + if (entry != null) { + cache.put(hash, entry); + } + return entry; + } + + private Entry doResolveEntry(String domain, String hash) + throws DnsException, TextParseException, UnknownHostException { + try { + ByteArray.toHexString(Algorithm.decode32(hash)); + } catch (Exception e) { + throw new DnsException(TypeEnum.OTHER_ERROR, "invalid base32 hash: " + hash); + } + TXTRecord txtRecord = LookUpTxt.lookUpTxt(hash, domain); + if (txtRecord == null) { + return null; + } + String txt = LookUpTxt.joinTXTRecord(txtRecord); + + Entry entry = null; + if (txt.startsWith(Entry.branchPrefix)) { + entry = BranchEntry.parseEntry(txt); + } else if (txt.startsWith(Entry.linkPrefix)) { + entry = LinkEntry.parseEntry(txt); + } else if (txt.startsWith(Entry.nodesPrefix)) { + entry = NodesEntry.parseEntry(txt); + } + + if (entry == null) { + throw new DnsException(TypeEnum.NO_ENTRY_FOUND, + String.format("hash:%s, domain:%s, txt:%s", hash, domain, txt)); + } + + String wantHash = Algorithm.encode32AndTruncate(entry.toString()); + if (!wantHash.equals(hash)) { + throw new DnsException(TypeEnum.HASH_MISS_MATCH, + String.format("hash mismatch, want: [%s], really: [%s], content: [%s]", wantHash, hash, + entry)); + } + return entry; + } + + public RandomIterator newIterator() { + RandomIterator randomIterator = new RandomIterator(this); + for (String urlScheme : Parameter.p2pConfig.getTreeUrls()) { + try { + randomIterator.addTree(urlScheme); + } catch (DnsException e) { + logger.error("AddTree failed " + urlScheme, e); + } + } + return randomIterator; + } + + public void close() { + if (syncer != null) { + syncer.shutdown(); + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/sync/ClientTree.java b/p2p/src/main/java/org/tron/p2p/dns/sync/ClientTree.java new file mode 100644 index 00000000000..4ca4b4f698c --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/sync/ClientTree.java @@ -0,0 +1,195 @@ +package org.tron.p2p.dns.sync; + +import java.net.UnknownHostException; +import java.security.SignatureException; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.dns.DnsNode; +import org.tron.p2p.dns.tree.Entry; +import org.tron.p2p.dns.tree.LinkEntry; +import org.tron.p2p.dns.tree.NodesEntry; +import org.tron.p2p.dns.tree.RootEntry; +import org.tron.p2p.exception.DnsException; +import org.xbill.DNS.TextParseException; + +@Slf4j(topic = "net") +public class ClientTree { + + // used for construct + private final Client client; + @Getter + @Setter + private LinkEntry linkEntry; + private final LinkCache linkCache; + + // used for check + private long lastValidateTime; + private int lastSeq = -1; + + // used for sync + @Getter + @Setter + private RootEntry root; + private SubtreeSync enrSync; + private SubtreeSync linkSync; + + //all links in this tree + private Set curLinks; + private String linkGCRoot; + + private final Random random; + + public ClientTree(Client c) { + this.client = c; + this.linkCache = new LinkCache(); + random = new Random(); + } + + public ClientTree(Client c, LinkCache lc, LinkEntry loc) { + this.client = c; + this.linkCache = lc; + this.linkEntry = loc; + curLinks = new HashSet<>(); + random = new Random(); + } + + public boolean[] syncAll(Map entries) + throws DnsException, UnknownHostException, + SignatureException, TextParseException { + boolean[] isRootUpdate = updateRoot(); + linkSync.resolveAll(entries); + enrSync.resolveAll(entries); + return isRootUpdate; + } + + // retrieves a single entry of the tree. The Node return value is non-nil if the entry was a node. + public synchronized DnsNode syncRandom() + throws DnsException, SignatureException, TextParseException, UnknownHostException { + if (rootUpdateDue()) { + updateRoot(); + } + + // Link tree sync has priority, run it to completion before syncing ENRs. + if (!linkSync.done()) { + syncNextLink(); + return null; + } + gcLinks(); + + // Sync next random entry in ENR tree. Once every node has been visited, we simply + // start over. This is fine because entries are cached internally by the client LRU + // also by DNS resolvers. + if (enrSync.done()) { + enrSync = new SubtreeSync(client, linkEntry, root.getERoot(), false); + } + return syncNextRandomNode(); + } + + // checks if any meaningful action can be performed by syncRandom. + public boolean canSyncRandom() { + return rootUpdateDue() || !linkSync.done() || !enrSync.done() || enrSync.leaves == 0; + } + + // gcLinks removes outdated links from the global link cache. + // GC runs once when the link sync finishes. + public void gcLinks() { + if (!linkSync.done() || root.getLRoot().equals(linkGCRoot)) { + return; + } + linkCache.resetLinks(linkEntry.getRepresent(), curLinks); + linkGCRoot = root.getLRoot(); + } + + // traversal next link of missing + public void syncNextLink() throws DnsException, TextParseException, UnknownHostException { + String hash = linkSync.missing.peek(); + Entry entry = linkSync.resolveNext(hash); + linkSync.missing.poll(); + + if (entry instanceof LinkEntry) { + LinkEntry dest = (LinkEntry) entry; + linkCache.addLink(linkEntry.getRepresent(), dest.getRepresent()); + curLinks.add(dest.getRepresent()); + } + } + + // get one hash from enr missing randomly, then get random node from hash if hash is a leaf node + private DnsNode syncNextRandomNode() + throws DnsException, TextParseException, UnknownHostException { + int pos = random.nextInt(enrSync.missing.size()); + String hash = enrSync.missing.get(pos); + Entry entry = enrSync.resolveNext(hash); + enrSync.missing.remove(pos); + if (entry instanceof NodesEntry) { + NodesEntry nodesEntry = (NodesEntry) entry; + List nodeList = nodesEntry.getNodes(); + int size = nodeList.size(); + return nodeList.get(random.nextInt(size)); + } + logger.info("Get branch or link entry in syncNextRandomNode"); + return null; + } + + // updateRoot ensures that the given tree has an up-to-date root. + private boolean[] updateRoot() + throws TextParseException, DnsException, SignatureException, UnknownHostException { + logger.info("UpdateRoot {}", linkEntry.getDomain()); + lastValidateTime = System.currentTimeMillis(); + RootEntry rootEntry = client.resolveRoot(linkEntry); + if (rootEntry == null) { + return new boolean[] {false, false}; + } + if (rootEntry.getSeq() <= lastSeq) { + logger.info("The seq of url doesn't change, url:[{}], seq:{}", linkEntry.getRepresent(), + lastSeq); + return new boolean[] {false, false}; + } + + root = rootEntry; + lastSeq = rootEntry.getSeq(); + + boolean updateLRoot = false; + boolean updateERoot = false; + if (linkSync == null || !rootEntry.getLRoot().equals(linkSync.root)) { + linkSync = new SubtreeSync(client, linkEntry, rootEntry.getLRoot(), true); + curLinks = new HashSet<>();//clear all links + updateLRoot = true; + } else { + // if lroot is not changed, wo do not to sync the link tree + logger.info("The lroot of url doesn't change, url:[{}], lroot:[{}]", linkEntry.getRepresent(), + linkSync.root); + } + + if (enrSync == null || !rootEntry.getERoot().equals(enrSync.root)) { + enrSync = new SubtreeSync(client, linkEntry, rootEntry.getERoot(), false); + updateERoot = true; + } else { + // if eroot is not changed, wo do not to sync the enr tree + logger.info("The eroot of url doesn't change, url:[{}], eroot:[{}]", linkEntry.getRepresent(), + enrSync.root); + } + return new boolean[] {updateLRoot, updateERoot}; + } + + private boolean rootUpdateDue() { + boolean scheduledCheck = System.currentTimeMillis() > nextScheduledRootCheck(); + if (scheduledCheck) { + logger.info("Update root because of scheduledCheck, {}", linkEntry.getDomain()); + } + return root == null || scheduledCheck; + } + + public long nextScheduledRootCheck() { + return lastValidateTime + Client.recheckInterval * 1000L; + } + + public String toString() { + return linkEntry.toString(); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/sync/LinkCache.java b/p2p/src/main/java/org/tron/p2p/dns/sync/LinkCache.java new file mode 100644 index 00000000000..964fb0bcc99 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/sync/LinkCache.java @@ -0,0 +1,82 @@ +package org.tron.p2p.dns.sync; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; + + +@Slf4j(topic = "net") +public class LinkCache { + + @Getter + Map> backrefs; + @Getter + @Setter + private boolean changed; //if data in backrefs changes, we need to rebuild trees + + public LinkCache() { + backrefs = new HashMap<>(); + changed = false; + } + + // check if the urlScheme occurs in other trees + public boolean isContainInOtherLink(String urlScheme) { + return backrefs.containsKey(urlScheme) && !backrefs.get(urlScheme).isEmpty(); + } + + /** + * add the reference to backrefs + * + * @param parent the url tree that contains url tree `children` + * @param children url tree + */ + public void addLink(String parent, String children) { + Set refs = backrefs.getOrDefault(children, new HashSet<>()); + if (!refs.contains(parent)) { + changed = true; + } + refs.add(parent); + backrefs.put(children, refs); + } + + /** + * clears all links of the given tree. + * + * @param from tree's urlScheme + * @param keep links contained in this tree + */ + public void resetLinks(String from, final Set keep) { + List stk = new ArrayList<>(); + stk.add(from); + + while (!stk.isEmpty()) { + int size = stk.size(); + String item = stk.get(size - 1); + stk = stk.subList(0, size - 1); + + Iterator>> it = backrefs.entrySet().iterator(); + while (it.hasNext()) { + Entry> entry = it.next(); + String r = entry.getKey(); + Set refs = entry.getValue(); + if ((keep != null && keep.contains(r)) || !refs.contains(item)) { + continue; + } + this.changed = true; + refs.remove(item); + if (refs.isEmpty()) { + it.remove(); + stk.add(r); + } + } + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/sync/RandomIterator.java b/p2p/src/main/java/org/tron/p2p/dns/sync/RandomIterator.java new file mode 100644 index 00000000000..36d2cf224f1 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/sync/RandomIterator.java @@ -0,0 +1,126 @@ +package org.tron.p2p.dns.sync; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.tron.p2p.dns.DnsNode; +import org.tron.p2p.dns.tree.LinkEntry; +import org.tron.p2p.exception.DnsException; + + +@Slf4j(topic = "net") +public class RandomIterator implements Iterator { + + private final Client client; + private Map clientTrees; + @Getter + private DnsNode cur; + private final LinkCache linkCache; + private final Random random; + + public RandomIterator(Client client) { + this.client = client; + clientTrees = new ConcurrentHashMap<>(); + linkCache = new LinkCache(); + random = new Random(); + } + + //syncs random tree entries until it finds a node. + @Override + public DnsNode next() { + int i = 0; + while (i < Client.randomRetryTimes) { + i += 1; + ClientTree clientTree = pickTree(); + if (clientTree == null) { + logger.error("clientTree is null"); + return null; + } + logger.info("Choose clientTree:{} from {} ClientTree", + clientTree.getLinkEntry().getRepresent(), clientTrees.size()); + DnsNode dnsNode; + try { + dnsNode = clientTree.syncRandom(); + } catch (Exception e) { + logger.warn("Error in DNS random node sync, tree:{}, cause:[{}]", + clientTree.getLinkEntry().getDomain(), e.getMessage()); + continue; + } + if (dnsNode != null && dnsNode.getPreferInetSocketAddress() != null) { + return dnsNode; + } + } + return null; + } + + @Override + public boolean hasNext() { + this.cur = next(); + return this.cur != null; + } + + public void addTree(String url) throws DnsException { + LinkEntry linkEntry = LinkEntry.parseEntry(url); + linkCache.addLink("", linkEntry.getRepresent()); + } + + //the first random + private ClientTree pickTree() { + if (clientTrees == null) { + logger.info("clientTrees is null"); + return null; + } + if (linkCache.isChanged()) { + rebuildTrees(); + linkCache.setChanged(false); + } + + int size = clientTrees.size(); + List allTrees = new ArrayList<>(clientTrees.values()); + + return allTrees.get(random.nextInt(size)); + } + + // rebuilds the 'trees' map. + // if urlScheme is not contain in any other link, wo delete it from clientTrees + // then create one ClientTree using this urlScheme, add it to clientTrees + private void rebuildTrees() { + logger.info("rebuildTrees..."); + Iterator> it = clientTrees.entrySet().iterator(); + while (it.hasNext()) { + Entry entry = it.next(); + String urlScheme = entry.getKey(); + if (!linkCache.isContainInOtherLink(urlScheme)) { + logger.info("remove tree from trees:{}", urlScheme); + it.remove(); + } + } + + for (Entry> entry : linkCache.backrefs.entrySet()) { + String urlScheme = entry.getKey(); + if (!clientTrees.containsKey(urlScheme)) { + try { + LinkEntry linkEntry = LinkEntry.parseEntry(urlScheme); + clientTrees.put(urlScheme, new ClientTree(client, linkCache, linkEntry)); + logger.info("add tree to clientTrees:{}", urlScheme); + } catch (DnsException e) { + logger.error("Parse LinkEntry failed", e); + } + } + } + logger.info("Exist clientTrees: {}", StringUtils.join(clientTrees.keySet(), ",")); + } + + public void close() { + clientTrees = null; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/sync/SubtreeSync.java b/p2p/src/main/java/org/tron/p2p/dns/sync/SubtreeSync.java new file mode 100644 index 00000000000..3b48ad523c6 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/sync/SubtreeSync.java @@ -0,0 +1,74 @@ +package org.tron.p2p.dns.sync; + +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.dns.tree.BranchEntry; +import org.tron.p2p.dns.tree.Entry; +import org.tron.p2p.dns.tree.LinkEntry; +import org.tron.p2p.dns.tree.NodesEntry; +import org.tron.p2p.exception.DnsException; +import org.tron.p2p.exception.DnsException.TypeEnum; +import org.xbill.DNS.TextParseException; + +@Slf4j(topic = "net") +public class SubtreeSync { + + public Client client; + public LinkEntry linkEntry; + + public String root; + + public boolean link; + public int leaves; + + public LinkedList missing; + + public SubtreeSync(Client c, LinkEntry linkEntry, String root, boolean link) { + this.client = c; + this.linkEntry = linkEntry; + this.root = root; + this.link = link; + this.leaves = 0; + missing = new LinkedList<>(); + missing.add(root); + } + + public boolean done() { + return missing.isEmpty(); + } + + public void resolveAll(Map dest) + throws DnsException, UnknownHostException, TextParseException { + while (!done()) { + String hash = missing.peek(); + Entry entry = resolveNext(hash); + if (entry != null) { + dest.put(hash, entry); + } + missing.poll(); + } + } + + public Entry resolveNext(String hash) + throws DnsException, TextParseException, UnknownHostException { + Entry entry = client.resolveEntry(linkEntry.getDomain(), hash); + if (entry instanceof NodesEntry) { + if (link) { + throw new DnsException(TypeEnum.NODES_IN_LINK_TREE, ""); + } + leaves++; + } else if (entry instanceof LinkEntry) { + if (!link) { + throw new DnsException(TypeEnum.LINK_IN_NODES_TREE, ""); + } + leaves++; + } else if (entry instanceof BranchEntry) { + BranchEntry branchEntry = (BranchEntry) entry; + missing.addAll(Arrays.asList(branchEntry.getChildren())); + } + return entry; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/tree/Algorithm.java b/p2p/src/main/java/org/tron/p2p/dns/tree/Algorithm.java new file mode 100644 index 00000000000..185b4261415 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/tree/Algorithm.java @@ -0,0 +1,150 @@ +package org.tron.p2p.dns.tree; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.SignatureException; +import java.util.Arrays; +import java.util.Base64; +import org.apache.commons.lang3.StringUtils; +import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.crypto.ec.CustomNamedCurves; +import org.bouncycastle.crypto.params.ECDomainParameters; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.encoders.Base32; +import org.tron.p2p.utils.ByteArray; +import org.web3j.crypto.ECKeyPair; +import org.web3j.crypto.Hash; +import org.web3j.crypto.Sign; +import org.web3j.crypto.Sign.SignatureData; + +public class Algorithm { + + private static final int truncateLength = 26; + public static final String padding = "="; + + /** + * return compress public key with hex + */ + public static String compressPubKey(BigInteger pubKey) { + String pubKeyYPrefix = pubKey.testBit(0) ? "03" : "02"; + String pubKeyHex = pubKey.toString(16); + String pubKeyX = pubKeyHex.substring(0, 64); + String hexPub = pubKeyYPrefix + pubKeyX; + return hexPub; + } + + public static String decompressPubKey(String hexPubKey) { + X9ECParameters CURVE_PARAMS = CustomNamedCurves.getByName("secp256k1"); + ECDomainParameters CURVE = + new ECDomainParameters( + CURVE_PARAMS.getCurve(), + CURVE_PARAMS.getG(), + CURVE_PARAMS.getN(), + CURVE_PARAMS.getH()); + byte[] pubKey = ByteArray.fromHexString(hexPubKey); + ECPoint ecPoint = CURVE.getCurve().decodePoint(pubKey); + byte[] encoded = ecPoint.getEncoded(false); + BigInteger n = new BigInteger(1, Arrays.copyOfRange(encoded, 1, encoded.length)); + return ByteArray.toHexString(n.toByteArray()); + } + + public static ECKeyPair generateKeyPair(String privateKey) { + BigInteger privKey = new BigInteger(privateKey, 16); + BigInteger pubKey = Sign.publicKeyFromPrivate(privKey); + return new ECKeyPair(privKey, pubKey); + } + + /** + * The produced signature is in the 65-byte [R || S || V] format where V is 0 or 1. + */ + public static byte[] sigData(String msg, String privateKey) { + ECKeyPair keyPair = generateKeyPair(privateKey); + Sign.SignatureData signature = Sign.signMessage(msg.getBytes(), keyPair, true); + byte[] data = new byte[65]; + System.arraycopy(signature.getR(), 0, data, 0, 32); + System.arraycopy(signature.getS(), 0, data, 32, 32); + data[64] = signature.getV()[0]; + return data; + } + + public static BigInteger recoverPublicKey(String msg, byte[] sig) throws SignatureException { + int recId = sig[64]; + if (recId < 27) { + recId += 27; + } + Sign.SignatureData signature = new SignatureData((byte) recId, ByteArray.subArray(sig, 0, 32), + ByteArray.subArray(sig, 32, 64)); + return Sign.signedMessageToKey(msg.getBytes(), signature); + } + + /** + * @param publicKey uncompress hex publicKey + * @param msg to be hashed message + */ + public static boolean verifySignature(String publicKey, String msg, byte[] sig) + throws SignatureException { + BigInteger pubKey = new BigInteger(publicKey, 16); + BigInteger pubKeyRecovered = recoverPublicKey(msg, sig); + return pubKey.equals(pubKeyRecovered); + } + + //we only use fix width hash + public static boolean isValidHash(String base32Hash) { + if (base32Hash == null || base32Hash.length() != truncateLength || base32Hash.contains("\r") + || base32Hash.contains("\n")) { + return false; + } + StringBuilder sb = new StringBuilder(base32Hash); + for (int i = 0; i < 32 - truncateLength; i++) { + sb.append(padding); + } + try { + Base32.decode(sb.toString()); + } catch (Exception e) { + return false; + } + return true; + } + + public static String encode64(byte[] content) { + String base64Content = new String(Base64.getUrlEncoder().encode(content), + StandardCharsets.UTF_8); + return StringUtils.stripEnd(base64Content, padding); + } + + // An Encoding is a radix 64 encoding/decoding scheme, defined by a + // 64-character alphabet. The most common encoding is the "base64" + // encoding defined in RFC 4648 and used in MIME (RFC 2045) and PEM + // (RFC 1421). RFC 4648 also defines an alternate encoding, which is + // the standard encoding with - and _ substituted for + and /. + public static byte[] decode64(String base64Content) { + return Base64.getUrlDecoder().decode(base64Content); + } + + public static String encode32(byte[] content) { + String base32Content = new String(Base32.encode(content), StandardCharsets.UTF_8); + return StringUtils.stripEnd(base32Content, padding); + } + + /** + * first get the hash of string, then get first 16 letter, last encode it with base32 + */ + public static String encode32AndTruncate(String content) { + return encode32(ByteArray.subArray(Hash.sha3(content.getBytes()), 0, 16)) + .substring(0, truncateLength); + } + + /** + * if content's length is not multiple of 8, we padding it + */ + public static byte[] decode32(String content) { + int left = content.length() % 8; + StringBuilder sb = new StringBuilder(content); + if (left > 0) { + for (int i = 0; i < 8 - left; i++) { + sb.append(padding); + } + } + return Base32.decode(sb.toString()); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/tree/BranchEntry.java b/p2p/src/main/java/org/tron/p2p/dns/tree/BranchEntry.java new file mode 100644 index 00000000000..35c55d84eda --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/tree/BranchEntry.java @@ -0,0 +1,32 @@ +package org.tron.p2p.dns.tree; + +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; + +@Slf4j(topic = "net") +public class BranchEntry implements Entry { + + private static final String splitSymbol = ","; + @Getter + private String[] children; + + public BranchEntry(String[] children) { + this.children = children; + } + + public static BranchEntry parseEntry(String e) { + String content = e.substring(branchPrefix.length()); + if (StringUtils.isEmpty(content)) { + logger.info("children size is 0, e:[{}]", e); + return new BranchEntry(new String[0]); + } else { + return new BranchEntry(content.split(splitSymbol)); + } + } + + @Override + public String toString() { + return branchPrefix + StringUtils.join(children, splitSymbol); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/tree/Entry.java b/p2p/src/main/java/org/tron/p2p/dns/tree/Entry.java new file mode 100644 index 00000000000..e3ea47b137e --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/tree/Entry.java @@ -0,0 +1,10 @@ +package org.tron.p2p.dns.tree; + + +public interface Entry { + + String rootPrefix = "tree-root-v1:"; + String linkPrefix = "tree://"; + String branchPrefix = "tree-branch:"; + String nodesPrefix = "nodes:"; +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/tree/LinkEntry.java b/p2p/src/main/java/org/tron/p2p/dns/tree/LinkEntry.java new file mode 100644 index 00000000000..7e0255afd4a --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/tree/LinkEntry.java @@ -0,0 +1,53 @@ +package org.tron.p2p.dns.tree; + +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.exception.DnsException; +import org.tron.p2p.exception.DnsException.TypeEnum; +import org.tron.p2p.utils.ByteArray; + +@Slf4j(topic = "net") +public class LinkEntry implements Entry { + + @Getter + private final String represent; + @Getter + private final String domain; + @Getter + private final String unCompressHexPublicKey; + + public LinkEntry(String represent, String domain, String unCompressHexPublicKey) { + this.represent = represent; + this.domain = domain; + this.unCompressHexPublicKey = unCompressHexPublicKey; + } + + public static LinkEntry parseEntry(String treeRepresent) throws DnsException { + if (!treeRepresent.startsWith(linkPrefix)) { + throw new DnsException(TypeEnum.INVALID_SCHEME_URL, + "scheme url must starts with :[" + Entry.linkPrefix + "], but get " + treeRepresent); + } + String[] items = treeRepresent.substring(linkPrefix.length()).split("@"); + if (items.length != 2) { + throw new DnsException(TypeEnum.NO_PUBLIC_KEY, "scheme url:" + treeRepresent); + } + String base32PublicKey = items[0]; + + try { + byte[] data = Algorithm.decode32(base32PublicKey); + String unCompressPublicKey = Algorithm.decompressPubKey(ByteArray.toHexString(data)); + return new LinkEntry(treeRepresent, items[1], unCompressPublicKey); + } catch (RuntimeException exception) { + throw new DnsException(TypeEnum.BAD_PUBLIC_KEY, "bad public key:" + base32PublicKey); + } + } + + public static String buildRepresent(String base32PubKey, String domain) { + return linkPrefix + base32PubKey + "@" + domain; + } + + @Override + public String toString() { + return represent; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/tree/NodesEntry.java b/p2p/src/main/java/org/tron/p2p/dns/tree/NodesEntry.java new file mode 100644 index 00000000000..d7ca7a6503e --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/tree/NodesEntry.java @@ -0,0 +1,39 @@ +package org.tron.p2p.dns.tree; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.net.UnknownHostException; +import java.util.List; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.dns.DnsNode; +import org.tron.p2p.exception.DnsException; +import org.tron.p2p.exception.DnsException.TypeEnum; + +@Slf4j(topic = "net") +public class NodesEntry implements Entry { + + private final String represent; + @Getter + private final List nodes; + + public NodesEntry(String represent, List nodes) { + this.represent = represent; + this.nodes = nodes; + } + + public static NodesEntry parseEntry(String e) throws DnsException { + String content = e.substring(nodesPrefix.length()); + List nodeList; + try { + nodeList = DnsNode.decompress(content.replace("\"","")); + } catch (InvalidProtocolBufferException | UnknownHostException ex) { + throw new DnsException(TypeEnum.INVALID_NODES, ex); + } + return new NodesEntry(e, nodeList); + } + + @Override + public String toString() { + return represent; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/tree/RootEntry.java b/p2p/src/main/java/org/tron/p2p/dns/tree/RootEntry.java new file mode 100644 index 00000000000..4c1998450c2 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/tree/RootEntry.java @@ -0,0 +1,113 @@ +package org.tron.p2p.dns.tree; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import java.security.SignatureException; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.tron.p2p.exception.DnsException; +import org.tron.p2p.exception.DnsException.TypeEnum; +import org.tron.p2p.protos.Discover.DnsRoot; +import org.tron.p2p.utils.ByteArray; + +@Slf4j(topic = "net") +public class RootEntry implements Entry { + + @Getter + private DnsRoot dnsRoot; + + public RootEntry(DnsRoot dnsRoot) { + this.dnsRoot = dnsRoot; + } + + public String getERoot() { + return new String(dnsRoot.getTreeRoot().getERoot().toByteArray()); + } + + public String getLRoot() { + return new String(dnsRoot.getTreeRoot().getLRoot().toByteArray()); + } + + public int getSeq() { + return dnsRoot.getTreeRoot().getSeq(); + } + + public void setSeq(int seq) { + DnsRoot.TreeRoot.Builder builder = dnsRoot.getTreeRoot().toBuilder(); + builder.setSeq(seq); + + DnsRoot.Builder dnsRootBuilder = dnsRoot.toBuilder(); + dnsRootBuilder.setTreeRoot(builder.build()); + + this.dnsRoot = dnsRootBuilder.build(); + } + + public byte[] getSignature() { + return Algorithm.decode64(new String(dnsRoot.getSignature().toByteArray())); + } + + public void setSignature(byte[] signature) { + DnsRoot.Builder dnsRootBuilder = dnsRoot.toBuilder(); + dnsRootBuilder.setSignature(ByteString.copyFrom(Algorithm.encode64(signature).getBytes())); + this.dnsRoot = dnsRootBuilder.build(); + } + + public RootEntry(String eRoot, String lRoot, int seq) { + DnsRoot.TreeRoot.Builder builder = DnsRoot.TreeRoot.newBuilder(); + builder.setERoot(ByteString.copyFrom(eRoot.getBytes())); + builder.setLRoot(ByteString.copyFrom(lRoot.getBytes())); + builder.setSeq(seq); + + DnsRoot.Builder dnsRootBuilder = DnsRoot.newBuilder(); + dnsRootBuilder.setTreeRoot(builder.build()); + this.dnsRoot = dnsRootBuilder.build(); + } + + public static RootEntry parseEntry(String e) throws DnsException { + String value = e.substring(rootPrefix.length()); + DnsRoot dnsRoot1; + try { + dnsRoot1 = DnsRoot.parseFrom(Algorithm.decode64(value)); + } catch (InvalidProtocolBufferException ex) { + throw new DnsException(TypeEnum.INVALID_ROOT, String.format("proto=[%s]", e), ex); + } + + byte[] signature = Algorithm.decode64(new String(dnsRoot1.getSignature().toByteArray())); + if (signature.length != 65) { + throw new DnsException(TypeEnum.INVALID_SIGNATURE, + String.format("signature's length(%d) != 65, signature: %s", signature.length, + ByteArray.toHexString(signature))); + } + + return new RootEntry(dnsRoot1); + } + + public static RootEntry parseEntry(String e, String publicKey, String domain) + throws SignatureException, DnsException { + logger.info("Domain:{}, public key:{}", domain, publicKey); + RootEntry rootEntry = parseEntry(e); + boolean verify = Algorithm.verifySignature(publicKey, rootEntry.toString(), + rootEntry.getSignature()); + if (!verify) { + throw new DnsException(TypeEnum.INVALID_SIGNATURE, + String.format("verify signature failed! data:[%s], publicKey:%s, domain:%s", e, publicKey, + domain)); + } + if (!Algorithm.isValidHash(rootEntry.getERoot()) || !Algorithm.isValidHash( + rootEntry.getLRoot())) { + throw new DnsException(TypeEnum.INVALID_CHILD, + "eroot:" + rootEntry.getERoot() + " lroot:" + rootEntry.getLRoot()); + } + logger.info("Get dnsRoot:[{}]", rootEntry.dnsRoot.toString()); + return rootEntry; + } + + @Override + public String toString() { + return dnsRoot.getTreeRoot().toString(); + } + + public String toFormat() { + return rootPrefix + Algorithm.encode64(dnsRoot.toByteArray()); + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/tree/Tree.java b/p2p/src/main/java/org/tron/p2p/dns/tree/Tree.java new file mode 100644 index 00000000000..7b40dc2d1ab --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/tree/Tree.java @@ -0,0 +1,247 @@ +package org.tron.p2p.dns.tree; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.math.BigInteger; +import java.net.UnknownHostException; +import java.security.SignatureException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.tron.p2p.dns.DnsNode; +import org.tron.p2p.dns.update.AliClient; +import org.tron.p2p.exception.DnsException; +import org.tron.p2p.exception.DnsException.TypeEnum; +import org.tron.p2p.utils.ByteArray; + +@Slf4j(topic = "net") +public class Tree { + + public static final int HashAbbrevSize = 1 + 16 * 13 / 8; // Size of an encoded hash (plus comma) + public static final int MaxChildren = 370 / HashAbbrevSize; // 13 children + + @Getter + @Setter + private RootEntry rootEntry; + @Getter + private Map entries; + private String privateKey; + @Getter + private String base32PublicKey; + + public Tree() { + init(); + } + + private void init() { + this.entries = new ConcurrentHashMap<>(); + } + + private Entry build(List leafs) { + if (leafs.size() == 1) { + return leafs.get(0); + } + if (leafs.size() <= MaxChildren) { + String[] children = new String[leafs.size()]; + for (int i = 0; i < leafs.size(); i++) { + String subDomain = Algorithm.encode32AndTruncate(leafs.get(i).toString()); + children[i] = subDomain; + this.entries.put(subDomain, leafs.get(i)); + } + return new BranchEntry(children); + } + + //every batch size of leaf entry construct a branch + List subtrees = new ArrayList<>(); + while (!leafs.isEmpty()) { + int total = leafs.size(); + int n = StrictMath.min(MaxChildren, total); + Entry branch = build(leafs.subList(0, n)); + + leafs = leafs.subList(n, total); + subtrees.add(branch); + + String subDomain = Algorithm.encode32AndTruncate(branch.toString()); + this.entries.put(subDomain, branch); + } + return build(subtrees); + } + + public void makeTree(int seq, List enrs, List links, String privateKey) + throws DnsException { + List nodesEntryList = new ArrayList<>(); + for (String enr : enrs) { + nodesEntryList.add(NodesEntry.parseEntry(enr)); + } + + List linkEntryList = new ArrayList<>(); + for (String link : links) { + linkEntryList.add(LinkEntry.parseEntry(link)); + } + + init(); + + Entry eRoot = build(nodesEntryList); + String eRootStr = Algorithm.encode32AndTruncate(eRoot.toString()); + entries.put(eRootStr, eRoot); + + Entry lRoot = build(linkEntryList); + String lRootStr = Algorithm.encode32AndTruncate(lRoot.toString()); + entries.put(lRootStr, lRoot); + + setRootEntry(new RootEntry(eRootStr, lRootStr, seq)); + + if (StringUtils.isNotEmpty(privateKey)) { + this.privateKey = privateKey; + sign(); + } + } + + public void sign() throws DnsException { + if (StringUtils.isEmpty(privateKey)) { + return; + } + byte[] sig = Algorithm.sigData(rootEntry.toString(), privateKey); //message don't include prefix + rootEntry.setSignature(sig); + + BigInteger publicKeyInt = Algorithm.generateKeyPair(privateKey).getPublicKey(); + String unCompressPublicKey = ByteArray.toHexString(publicKeyInt.toByteArray()); + + //verify ourselves + boolean verified; + try { + verified = Algorithm.verifySignature(unCompressPublicKey, rootEntry.toString(), + rootEntry.getSignature()); + } catch (SignatureException e) { + throw new DnsException(TypeEnum.INVALID_SIGNATURE, e); + } + if (!verified) { + throw new DnsException(TypeEnum.INVALID_SIGNATURE, ""); + } + String hexPub = Algorithm.compressPubKey(publicKeyInt); + this.base32PublicKey = Algorithm.encode32(ByteArray.fromHexString(hexPub)); + } + + public static List merge(List nodes, int maxMergeSize) { + Collections.sort(nodes); + List enrs = new ArrayList<>(); + int networkA = -1; + List sub = new ArrayList<>(); + for (DnsNode dnsNode : nodes) { + if ((networkA > -1 && dnsNode.getNetworkA() != networkA) || sub.size() >= maxMergeSize) { + enrs.add(Entry.nodesPrefix + DnsNode.compress(sub)); + sub.clear(); + } + sub.add(dnsNode); + networkA = dnsNode.getNetworkA(); + } + if (!sub.isEmpty()) { + enrs.add(Entry.nodesPrefix + DnsNode.compress(sub)); + } + return enrs; + } + + // hash => lower(hash).domain + public Map toTXT(String rootDomain) { + Map dnsRecords = new HashMap<>(); + if (StringUtils.isNoneEmpty(rootDomain)) { + dnsRecords.put(rootDomain, rootEntry.toFormat()); + } else { + dnsRecords.put(AliClient.aliyunRoot, rootEntry.toFormat()); + } + for (Map.Entry item : entries.entrySet()) { + String hash = item.getKey(); + String newKey = StringUtils.isNoneEmpty(rootDomain) ? hash + "." + rootDomain : hash; + dnsRecords.put(newKey.toLowerCase(Locale.ROOT), item.getValue().toString()); + } + return dnsRecords; + } + + public int getSeq() { + return rootEntry.getSeq(); + } + + public void setSeq(int seq) { + rootEntry.setSeq(seq); + } + + public List getLinksEntry() { + List linkList = new ArrayList<>(); + for (Entry entry : entries.values()) { + if (entry instanceof LinkEntry) { + LinkEntry linkEntry = (LinkEntry) entry; + linkList.add(linkEntry.toString()); + } + } + return linkList; + } + + public Map getLinksMap() { + Map linksMap = new HashMap<>(); + entries.entrySet().stream() + .filter(p -> p.getValue() instanceof LinkEntry) + .forEach(p -> linksMap.put(p.getKey(), p.getValue())); + return linksMap; + } + + public List getBranchesEntry() { + List branches = new ArrayList<>(); + for (Entry entry : entries.values()) { + if (entry instanceof BranchEntry) { + BranchEntry branchEntry = (BranchEntry) entry; + branches.add(branchEntry.toString()); + } + } + return branches; + } + + public List getNodesEntry() { + List nodesEntryList = new ArrayList<>(); + for (Entry entry : entries.values()) { + if (entry instanceof NodesEntry) { + NodesEntry nodesEntry = (NodesEntry) entry; + nodesEntryList.add(nodesEntry.toString()); + } + } + return nodesEntryList; + } + + public Map getNodesMap() { + Map nodesMap = new HashMap<>(); + entries.entrySet().stream() + .filter(p -> p.getValue() instanceof NodesEntry) + .forEach(p -> nodesMap.put(p.getKey(), p.getValue())); + return nodesMap; + } + + public void setEntries(Map entries) { + this.entries = entries; + } + + /** + * get nodes from entries dynamically. when sync first time, entries change as time + */ + public List getDnsNodes() { + List nodesEntryList = getNodesEntry(); + List nodes = new ArrayList<>(); + for (String nodesEntry : nodesEntryList) { + String joinStr = nodesEntry.substring(Entry.nodesPrefix.length()); + List subNodes; + try { + subNodes = DnsNode.decompress(joinStr); + } catch (InvalidProtocolBufferException | UnknownHostException e) { + logger.error("", e); + continue; + } + nodes.addAll(subNodes); + } + return nodes; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/update/AliClient.java b/p2p/src/main/java/org/tron/p2p/dns/update/AliClient.java new file mode 100644 index 00000000000..df67ffee5cd --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/update/AliClient.java @@ -0,0 +1,341 @@ +package org.tron.p2p.dns.update; + +import com.aliyun.alidns20150109.Client; +import com.aliyun.alidns20150109.models.AddDomainRecordRequest; +import com.aliyun.alidns20150109.models.AddDomainRecordResponse; +import com.aliyun.alidns20150109.models.DeleteDomainRecordRequest; +import com.aliyun.alidns20150109.models.DeleteDomainRecordResponse; +import com.aliyun.alidns20150109.models.DeleteSubDomainRecordsRequest; +import com.aliyun.alidns20150109.models.DeleteSubDomainRecordsResponse; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsRequest; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsResponse; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecordsRecord; +import com.aliyun.alidns20150109.models.UpdateDomainRecordRequest; +import com.aliyun.alidns20150109.models.UpdateDomainRecordResponse; +import com.aliyun.teaopenapi.models.Config; +import java.text.NumberFormat; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.tron.p2p.dns.DnsNode; +import org.tron.p2p.dns.tree.LinkEntry; +import org.tron.p2p.dns.tree.NodesEntry; +import org.tron.p2p.dns.tree.RootEntry; +import org.tron.p2p.dns.tree.Tree; +import org.tron.p2p.exception.DnsException; + +@Slf4j(topic = "net") +public class AliClient implements Publish { + + private final Long domainRecordsPageSize = 20L; + private final int maxRetryCount = 3; + private final int successCode = 200; + private final long retryWaitTime = 30; + private final int treeNodeTTL = 24 * 60 * 60; + private int lastSeq = 0; + private Set serverNodes; + private final Client aliDnsClient; + private double changeThreshold; + public static final String aliyunRoot = "@"; + + public AliClient(String endpoint, String accessKeyId, String accessKeySecret, + double changeThreshold) throws Exception { + Config config = new Config(); + config.accessKeyId = accessKeyId; + config.accessKeySecret = accessKeySecret; + config.endpoint = endpoint; + this.changeThreshold = changeThreshold; + this.serverNodes = new HashSet<>(); + aliDnsClient = new Client(config); + } + + @Override + public void testConnect() throws Exception { + } + + @Override + public void deploy(String domainName, Tree t) throws DnsException { + try { + Map existing = collectRecords( + domainName); + logger.info("Find {} TXT records, {} nodes for {}", existing.size(), serverNodes.size(), + domainName); + String represent = LinkEntry.buildRepresent(t.getBase32PublicKey(), domainName); + logger.info("Trying to publish {}", represent); + t.setSeq(this.lastSeq + 1); + t.sign(); //seq changed, wo need to sign again + Map records = t.toTXT(null); + + Set treeNodes = new HashSet<>(t.getDnsNodes()); + treeNodes.removeAll(serverNodes); // tree - dns + int addNodeSize = treeNodes.size(); + + Set set1 = new HashSet<>(serverNodes); + treeNodes = new HashSet<>(t.getDnsNodes()); + set1.removeAll(treeNodes); // dns - tree + int deleteNodeSize = set1.size(); + + if (serverNodes.isEmpty() + || (addNodeSize + deleteNodeSize) / (double) serverNodes.size() >= changeThreshold) { + String comment = String.format("Tree update of %s at seq %d", domainName, t.getSeq()); + logger.info(comment); + submitChanges(domainName, records, existing); + } else { + NumberFormat nf = NumberFormat.getNumberInstance(); + nf.setMaximumFractionDigits(4); + double changePercent = (addNodeSize + deleteNodeSize) / (double) serverNodes.size(); + logger.info( + "Sum of node add & delete percent {} is below changeThreshold {}, skip this changes", + nf.format(changePercent), changeThreshold); + } + serverNodes.clear(); + } catch (Exception e) { + throw new DnsException(DnsException.TypeEnum.DEPLOY_DOMAIN_FAILED, e); + } + } + + @Override + public boolean deleteDomain(String domainName) throws Exception { + DeleteSubDomainRecordsRequest request = new DeleteSubDomainRecordsRequest(); + request.setDomainName(domainName); + DeleteSubDomainRecordsResponse response = aliDnsClient.deleteSubDomainRecords(request); + return response.statusCode == successCode; + } + + // collects all TXT records below the given name. it also update lastSeq + @Override + public Map collectRecords( + String domain) throws Exception { + Map records = new HashMap<>(); + + String rootContent = null; + Set collectServerNodes = new HashSet<>(); + try { + DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest(); + request.setDomainName(domain); + request.setType("TXT"); + request.setPageSize(domainRecordsPageSize); + Long currentPageNum = 1L; + while (true) { + request.setPageNumber(currentPageNum); + DescribeDomainRecordsResponse response = aliDnsClient.describeDomainRecords(request); + if (response.statusCode == successCode) { + for (DescribeDomainRecordsResponseBodyDomainRecordsRecord r : response.getBody() + .getDomainRecords().getRecord()) { + String name = StringUtils.stripEnd(r.getRR(), "."); + records.put(name, r); + if (aliyunRoot.equalsIgnoreCase(name)) { + rootContent = r.value; + } + if (StringUtils.isNotEmpty(r.value) && r.value.startsWith( + org.tron.p2p.dns.tree.Entry.nodesPrefix)) { + NodesEntry nodesEntry; + try { + nodesEntry = NodesEntry.parseEntry(r.value); + List dnsNodes = nodesEntry.getNodes(); + collectServerNodes.addAll(dnsNodes); + } catch (DnsException e) { + //ignore + logger.error("Parse nodeEntry failed: {}", e.getMessage()); + } + } + } + if (currentPageNum * domainRecordsPageSize >= response.getBody().getTotalCount()) { + break; + } + currentPageNum++; + } else { + throw new Exception("Failed to request domain records"); + } + } + } catch (Exception e) { + logger.warn("Failed to collect domain records, error msg: {}", e.getMessage()); + throw e; + } + + if (rootContent != null) { + RootEntry rootEntry = RootEntry.parseEntry(rootContent); + this.lastSeq = rootEntry.getSeq(); + } + this.serverNodes = collectServerNodes; + return records; + } + + private void submitChanges(String domainName, + Map records, + Map existing) + throws Exception { + long ttl; + long addCount = 0; + long updateCount = 0; + long deleteCount = 0; + for (Map.Entry entry : records.entrySet()) { + boolean result = true; + ttl = treeNodeTTL; + if (entry.getKey().equals(aliyunRoot)) { + ttl = rootTTL; + } + if (!existing.containsKey(entry.getKey())) { + result = addRecord(domainName, entry.getKey(), entry.getValue(), ttl); + addCount++; + } else if (!entry.getValue().equals(existing.get(entry.getKey()).getValue()) + || existing.get(entry.getKey()).getTTL() != ttl) { + result = updateRecord(existing.get(entry.getKey()).getRecordId(), entry.getKey(), + entry.getValue(), ttl); + updateCount++; + } + + if (!result) { + throw new Exception("Adding or updating record failed"); + } + } + + for (String key : existing.keySet()) { + if (!records.containsKey(key)) { + deleteRecord(existing.get(key).getRecordId()); + deleteCount++; + } + } + logger.info("Published successfully, add count:{}, update count:{}, delete count:{}", + addCount, updateCount, deleteCount); + } + + public boolean addRecord(String domainName, String RR, String value, long ttl) throws Exception { + AddDomainRecordRequest request = new AddDomainRecordRequest(); + request.setDomainName(domainName); + request.setRR(RR); + request.setType("TXT"); + request.setValue(value); + request.setTTL(ttl); + int retryCount = 0; + while (true) { + AddDomainRecordResponse response = aliDnsClient.addDomainRecord(request); + if (response.statusCode == successCode) { + break; + } else if (retryCount < maxRetryCount) { + retryCount++; + Thread.sleep(retryWaitTime); + } else { + return false; + } + } + return true; + } + + public boolean updateRecord(String recId, String RR, String value, long ttl) throws Exception { + UpdateDomainRecordRequest request = new UpdateDomainRecordRequest(); + request.setRecordId(recId); + request.setRR(RR); + request.setType("TXT"); + request.setValue(value); + request.setTTL(ttl); + int retryCount = 0; + while (true) { + UpdateDomainRecordResponse response = aliDnsClient.updateDomainRecord(request); + if (response.statusCode == successCode) { + break; + } else if (retryCount < maxRetryCount) { + retryCount++; + Thread.sleep(retryWaitTime); + } else { + return false; + } + } + return true; + } + + public boolean deleteRecord(String recId) throws Exception { + DeleteDomainRecordRequest request = new DeleteDomainRecordRequest(); + request.setRecordId(recId); + int retryCount = 0; + while (true) { + DeleteDomainRecordResponse response = aliDnsClient.deleteDomainRecord(request); + if (response.statusCode == successCode) { + break; + } else if (retryCount < maxRetryCount) { + retryCount++; + Thread.sleep(retryWaitTime); + } else { + return false; + } + } + return true; + } + + public String getRecId(String domainName, String RR) { + String recId = null; + try { + DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest(); + request.setDomainName(domainName); + request.setRRKeyWord(RR); + DescribeDomainRecordsResponse response = aliDnsClient.describeDomainRecords(request); + if (response.getBody().getTotalCount() > 0) { + List recs = + response.getBody().getDomainRecords().getRecord(); + for (DescribeDomainRecordsResponseBodyDomainRecordsRecord rec : recs) { + if (rec.getRR().equalsIgnoreCase(RR)) { + recId = rec.getRecordId(); + break; + } + } + } + } catch (Exception e) { + logger.warn("Failed to get record id, error msg: {}", e.getMessage()); + } + return recId; + } + + public String update(String DomainName, String RR, String value, long ttl) { + String type = "TXT"; + String recId = null; + try { + String existRecId = getRecId(DomainName, RR); + if (existRecId == null || existRecId.isEmpty()) { + AddDomainRecordRequest request = new AddDomainRecordRequest(); + request.setDomainName(DomainName); + request.setRR(RR); + request.setType(type); + request.setValue(value); + request.setTTL(ttl); + AddDomainRecordResponse response = aliDnsClient.addDomainRecord(request); + recId = response.getBody().getRecordId(); + } else { + UpdateDomainRecordRequest request = new UpdateDomainRecordRequest(); + request.setRecordId(existRecId); + request.setRR(RR); + request.setType(type); + request.setValue(value); + request.setTTL(ttl); + UpdateDomainRecordResponse response = aliDnsClient.updateDomainRecord(request); + recId = response.getBody().getRecordId(); + } + } catch (Exception e) { + logger.warn("Failed to update or add domain record, error mag: {}", e.getMessage()); + } + + return recId; + } + + public boolean deleteByRR(String domainName, String RR) { + try { + String recId = getRecId(domainName, RR); + if (recId != null && !recId.isEmpty()) { + DeleteDomainRecordRequest request = new DeleteDomainRecordRequest(); + request.setRecordId(recId); + DeleteDomainRecordResponse response = aliDnsClient.deleteDomainRecord(request); + if (response.statusCode != successCode) { + return false; + } + } + } catch (Exception e) { + logger.warn("Failed to delete domain record, domain name: {}, RR: {}, error msg: {}", + domainName, RR, e.getMessage()); + return false; + } + return true; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/update/AwsClient.java b/p2p/src/main/java/org/tron/p2p/dns/update/AwsClient.java new file mode 100644 index 00000000000..f58a2231d8a --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/update/AwsClient.java @@ -0,0 +1,511 @@ +package org.tron.p2p.dns.update; + +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.tron.p2p.dns.DnsNode; +import org.tron.p2p.dns.tree.LinkEntry; +import org.tron.p2p.dns.tree.NodesEntry; +import org.tron.p2p.dns.tree.RootEntry; +import org.tron.p2p.dns.tree.Tree; +import org.tron.p2p.exception.DnsException; +import org.tron.p2p.exception.DnsException.TypeEnum; +import software.amazon.awssdk.auth.credentials.AwsCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.route53.Route53Client; +import software.amazon.awssdk.services.route53.model.Change; +import software.amazon.awssdk.services.route53.model.ChangeAction; +import software.amazon.awssdk.services.route53.model.ChangeBatch; +import software.amazon.awssdk.services.route53.model.ChangeResourceRecordSetsRequest; +import software.amazon.awssdk.services.route53.model.ChangeResourceRecordSetsResponse; +import software.amazon.awssdk.services.route53.model.ChangeStatus; +import software.amazon.awssdk.services.route53.model.GetChangeRequest; +import software.amazon.awssdk.services.route53.model.GetChangeResponse; +import software.amazon.awssdk.services.route53.model.HostedZone; +import software.amazon.awssdk.services.route53.model.ListHostedZonesByNameRequest; +import software.amazon.awssdk.services.route53.model.ListHostedZonesByNameResponse; +import software.amazon.awssdk.services.route53.model.ListResourceRecordSetsRequest; +import software.amazon.awssdk.services.route53.model.ListResourceRecordSetsResponse; +import software.amazon.awssdk.services.route53.model.RRType; +import software.amazon.awssdk.services.route53.model.ResourceRecord; +import software.amazon.awssdk.services.route53.model.ResourceRecordSet; + +@Slf4j(topic = "net") +public class AwsClient implements Publish { + + // Route53 limits change sets to 32k of 'RDATA size'. Change sets are also limited to + // 1000 items. UPSERTs count double. + // https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html#limits-api-requests-changeresourcerecordsets + public static final int route53ChangeSizeLimit = 32000; + public static final int route53ChangeCountLimit = 1000; + public static final int maxRetryLimit = 60; + private int lastSeq = 0; + private Route53Client route53Client; + private String zoneId; + private Set serverNodes; + private static final String symbol = "\""; + private static final String postfix = "."; + private double changeThreshold; + + public AwsClient(final String accessKey, final String accessKeySecret, + final String zoneId, final String region, double changeThreshold) throws DnsException { + if (StringUtils.isEmpty(accessKey) || StringUtils.isEmpty(accessKeySecret)) { + throw new DnsException(TypeEnum.DEPLOY_DOMAIN_FAILED, + "Need Route53 Access Key ID and secret to proceed"); + } + StaticCredentialsProvider staticCredentialsProvider = StaticCredentialsProvider.create( + new AwsCredentials() { + @Override + public String accessKeyId() { + return accessKey; + } + + @Override + public String secretAccessKey() { + return accessKeySecret; + } + }); + route53Client = Route53Client.builder() + .credentialsProvider(staticCredentialsProvider) + .region(Region.of(region)) + .build(); + this.zoneId = zoneId; + this.serverNodes = new HashSet<>(); + this.changeThreshold = changeThreshold; + } + + private void checkZone(String domain) { + if (StringUtils.isEmpty(this.zoneId)) { + this.zoneId = findZoneID(domain); + } + } + + private String findZoneID(String domain) { + logger.info("Finding Route53 Zone ID for {}", domain); + ListHostedZonesByNameRequest.Builder request = ListHostedZonesByNameRequest.builder(); + while (true) { + ListHostedZonesByNameResponse response = route53Client.listHostedZonesByName(request.build()); + for (HostedZone hostedZone : response.hostedZones()) { + if (isSubdomain(domain, hostedZone.name())) { + // example: /hostedzone/Z0404776204LVYA8EZNVH + return hostedZone.id().split("/")[2]; + } + } + if (Boolean.FALSE.equals(response.isTruncated())) { + break; + } + request.dnsName(response.dnsName()); + request.hostedZoneId(response.nextHostedZoneId()); + } + return null; + } + + @Override + public void testConnect() throws Exception { + ListHostedZonesByNameRequest.Builder request = ListHostedZonesByNameRequest.builder(); + while (true) { + ListHostedZonesByNameResponse response = route53Client.listHostedZonesByName(request.build()); + if (Boolean.FALSE.equals(response.isTruncated())) { + break; + } + request.dnsName(response.dnsName()); + request.hostedZoneId(response.nextHostedZoneId()); + } + } + + // uploads the given tree to Route53. + @Override + public void deploy(String domain, Tree tree) throws Exception { + checkZone(domain); + + Map existing = collectRecords(domain); + logger.info("Find {} TXT records, {} nodes for {}", existing.size(), serverNodes.size(), + domain); + String represent = LinkEntry.buildRepresent(tree.getBase32PublicKey(), domain); + logger.info("Trying to publish {}", represent); + + tree.setSeq(this.lastSeq + 1); + tree.sign(); //seq changed, wo need to sign again + Map records = tree.toTXT(domain); + + List changes = computeChanges(domain, records, existing); + + Set treeNodes = new HashSet<>(tree.getDnsNodes()); + treeNodes.removeAll(serverNodes); // tree - dns + int addNodeSize = treeNodes.size(); + + Set set1 = new HashSet<>(serverNodes); + treeNodes = new HashSet<>(tree.getDnsNodes()); + set1.removeAll(treeNodes); // dns - tree + int deleteNodeSize = set1.size(); + + if (serverNodes.isEmpty() + || (addNodeSize + deleteNodeSize) / (double) serverNodes.size() >= changeThreshold) { + String comment = String.format("Tree update of %s at seq %d", domain, tree.getSeq()); + logger.info(comment); + submitChanges(changes, comment); + } else { + NumberFormat nf = NumberFormat.getNumberInstance(); + nf.setMaximumFractionDigits(4); + double changePercent = (addNodeSize + deleteNodeSize) / (double) serverNodes.size(); + logger.info( + "Sum of node add & delete percent {} is below changeThreshold {}, skip this changes", + nf.format(changePercent), changeThreshold); + } + serverNodes.clear(); + } + + // removes all TXT records of the given domain. + @Override + public boolean deleteDomain(String rootDomain) throws Exception { + checkZone(rootDomain); + + Map existing = collectRecords(rootDomain); + logger.info("Find {} TXT records for {}", existing.size(), rootDomain); + + List changes = makeDeletionChanges(new HashMap<>(), existing); + + String comment = String.format("delete entree of %s", rootDomain); + submitChanges(changes, comment); + return true; + } + + // collects all TXT records below the given name. it also update lastSeq + @Override + public Map collectRecords(String rootDomain) throws Exception { + Map existing = new HashMap<>(); + ListResourceRecordSetsRequest.Builder request = ListResourceRecordSetsRequest.builder(); + request.hostedZoneId(zoneId); + int page = 0; + + String rootContent = null; + Set collectServerNodes = new HashSet<>(); + while (true) { + logger.info("Loading existing TXT records from name:{} zoneId:{} page:{}", rootDomain, zoneId, + page); + ListResourceRecordSetsResponse response = route53Client.listResourceRecordSets( + request.build()); + + List recordSetList = response.resourceRecordSets(); + for (ResourceRecordSet resourceRecordSet : recordSetList) { + if (!isSubdomain(resourceRecordSet.name(), rootDomain) + || resourceRecordSet.type() != RRType.TXT) { + continue; + } + List values = new ArrayList<>(); + for (ResourceRecord resourceRecord : resourceRecordSet.resourceRecords()) { + values.add(resourceRecord.value()); + } + RecordSet recordSet = new RecordSet(values.toArray(new String[0]), + resourceRecordSet.ttl()); + String name = StringUtils.stripEnd(resourceRecordSet.name(), postfix); + existing.put(name, recordSet); + + String content = StringUtils.join(values, ""); + content = StringUtils.strip(content, symbol); + if (rootDomain.equalsIgnoreCase(name)) { + rootContent = content; + } + if (content.startsWith(org.tron.p2p.dns.tree.Entry.nodesPrefix)) { + NodesEntry nodesEntry; + try { + nodesEntry = NodesEntry.parseEntry(content); + List dnsNodes = nodesEntry.getNodes(); + collectServerNodes.addAll(dnsNodes); + } catch (DnsException e) { + //ignore + logger.error("Parse nodeEntry failed: {}", e.getMessage()); + } + } + logger.info("Find name: {}", name); + } + + if (Boolean.FALSE.equals(response.isTruncated())) { + break; + } + // Set the cursor to the next batch. From the AWS docs: + // + // To display the next page of results, get the values of NextRecordName, + // NextRecordType, and NextRecordIdentifier (if any) from the response. Then submit + // another ListResourceRecordSets request, and specify those values for + // StartRecordName, StartRecordType, and StartRecordIdentifier. + request.startRecordIdentifier(response.nextRecordIdentifier()); + request.startRecordName(response.nextRecordName()); + request.startRecordType(response.nextRecordType()); + page += 1; + } + + if (rootContent != null) { + RootEntry rootEntry = RootEntry.parseEntry(rootContent); + this.lastSeq = rootEntry.getSeq(); + } + this.serverNodes = collectServerNodes; + return existing; + } + + // submits the given DNS changes to Route53. + public void submitChanges(List changes, String comment) { + if (changes.isEmpty()) { + logger.info("No DNS changes needed"); + return; + } + + List> batchChanges = splitChanges(changes, route53ChangeSizeLimit, + route53ChangeCountLimit); + + ChangeResourceRecordSetsResponse[] responses = + new ChangeResourceRecordSetsResponse[batchChanges.size()]; + for (int i = 0; i < batchChanges.size(); i++) { + logger.info("Submit {}/{} changes to Route53", i + 1, batchChanges.size()); + + ChangeBatch.Builder builder = ChangeBatch.builder(); + builder.changes(batchChanges.get(i)); + builder.comment(comment + String.format(" (%d/%d)", i + 1, batchChanges.size())); + + ChangeResourceRecordSetsRequest.Builder request = ChangeResourceRecordSetsRequest.builder(); + request.changeBatch(builder.build()); + request.hostedZoneId(this.zoneId); + + responses[i] = route53Client.changeResourceRecordSets(request.build()); + } + + // Wait for all change batches to propagate. + for (ChangeResourceRecordSetsResponse response : responses) { + logger.info("Waiting for change request {}", response.changeInfo().id()); + + GetChangeRequest.Builder request = GetChangeRequest.builder(); + request.id(response.changeInfo().id()); + + int count = 0; + while (true) { + GetChangeResponse changeResponse = route53Client.getChange(request.build()); + count += 1; + if (changeResponse.changeInfo().status() == ChangeStatus.INSYNC || count >= maxRetryLimit) { + break; + } + try { + Thread.sleep(15 * 1000); + } catch (InterruptedException e) { + // Upstream swallows the interrupt without restoring the flag, so this + // loop keeps polling until INSYNC or maxRetryLimit. Behaviour is + // preserved here; see the PR description for the deferred fix. + } + } + } + logger.info("Submit {} changes complete", changes.size()); + } + + // computeChanges creates DNS changes for the given set of DNS discovery records. + // records is the latest records to be put in Route53. + // The 'existing' arg is the set of records that already exist on Route53. + public List computeChanges(String domain, Map records, + Map existing) { + + List changes = new ArrayList<>(); + for (Entry entry : records.entrySet()) { + String path = entry.getKey(); + String value = entry.getValue(); + String newValue = splitTxt(value); + + // name's ttl in our domain will not changed, + // but this ttl on public dns server will decrease with time after request it first time + long ttl = path.equalsIgnoreCase(domain) ? rootTTL : treeNodeTTL; + + if (!existing.containsKey(path)) { + logger.info("Create {} = {}", path, value); + Change change = newTXTChange(ChangeAction.CREATE, path, ttl, newValue); + changes.add(change); + } else { + RecordSet recordSet = existing.get(path); + String preValue = StringUtils.join(recordSet.values, ""); + + if (!preValue.equalsIgnoreCase(newValue) || recordSet.ttl != ttl) { + logger.info("Updating {} from [{}] to [{}]", path, preValue, newValue); + if (path.equalsIgnoreCase(domain)) { + try { + RootEntry oldRoot = RootEntry.parseEntry(StringUtils.strip(preValue, symbol)); + RootEntry newRoot = RootEntry.parseEntry(StringUtils.strip(newValue, symbol)); + logger.info("Updating root from [{}] to [{}]", oldRoot.getDnsRoot(), + newRoot.getDnsRoot()); + } catch (DnsException e) { + //ignore + } + } + Change change = newTXTChange(ChangeAction.UPSERT, path, ttl, newValue); + changes.add(change); + } + } + } + + List deleteChanges = makeDeletionChanges(records, existing); + changes.addAll(deleteChanges); + + sortChanges(changes); + return changes; + } + + // creates record changes which delete all records not contained in 'keep' + public List makeDeletionChanges(Map keeps, + Map existing) { + List changes = new ArrayList<>(); + for (Entry entry : existing.entrySet()) { + String path = entry.getKey(); + RecordSet recordSet = entry.getValue(); + if (!keeps.containsKey(path)) { + logger.info("Delete {} = {}", path, StringUtils.join(existing.get(path).values, "")); + Change change = newTXTChange(ChangeAction.DELETE, path, recordSet.ttl, recordSet.values); + changes.add(change); + } + } + return changes; + } + + // ensures DNS changes are in leaf-added -> root-changed -> leaf-deleted order. + public static void sortChanges(List changes) { + changes.sort((o1, o2) -> { + if (getChangeOrder(o1) == getChangeOrder(o2)) { + return o1.resourceRecordSet().name().compareTo(o2.resourceRecordSet().name()); + } else { + return getChangeOrder(o1) - getChangeOrder(o2); + } + }); + } + + private static int getChangeOrder(Change change) { + switch (change.action()) { + case CREATE: + return 1; + case UPSERT: + return 2; + case DELETE: + return 3; + default: + return 4; + } + } + + // splits up DNS changes such that each change batch is smaller than the given RDATA limit. + private static List> splitChanges(List changes, int sizeLimit, + int countLimit) { + List> batchChanges = new ArrayList<>(); + + List subChanges = new ArrayList<>(); + int batchSize = 0; + int batchCount = 0; + for (Change change : changes) { + int changeCount = getChangeCount(change); + int changeSize = getChangeSize(change) * changeCount; + + if (batchCount + changeCount <= countLimit + && batchSize + changeSize <= sizeLimit) { + subChanges.add(change); + batchCount += changeCount; + batchSize += changeSize; + } else { + batchChanges.add(subChanges); + subChanges = new ArrayList<>(); + subChanges.add(change); + batchSize = changeSize; + batchCount = changeCount; + } + } + if (!subChanges.isEmpty()) { + batchChanges.add(subChanges); + } + return batchChanges; + } + + // returns the RDATA size of a DNS change. + private static int getChangeSize(Change change) { + int dataSize = 0; + for (ResourceRecord resourceRecord : change.resourceRecordSet().resourceRecords()) { + dataSize += resourceRecord.value().length(); + } + return dataSize; + } + + private static int getChangeCount(Change change) { + if (change.action() == ChangeAction.UPSERT) { + return 2; + } + return 1; + } + + public static boolean isSameChange(Change c1, Change c2) { + boolean isSame = c1.action().equals(c2.action()) + && c1.resourceRecordSet().ttl().longValue() == c2.resourceRecordSet().ttl().longValue() + && c1.resourceRecordSet().name().equals(c2.resourceRecordSet().name()) + && c1.resourceRecordSet().resourceRecords().size() == c2.resourceRecordSet() + .resourceRecords().size(); + if (!isSame) { + return false; + } + List list1 = c1.resourceRecordSet().resourceRecords(); + List list2 = c2.resourceRecordSet().resourceRecords(); + for (int i = 0; i < list1.size(); i++) { + if (!list1.get(i).equalsBySdkFields(list2.get(i))) { + return false; + } + } + return true; + } + + // creates a change to a TXT record. + public Change newTXTChange(ChangeAction action, String key, long ttl, String... values) { + ResourceRecordSet.Builder builder = ResourceRecordSet.builder() + .name(key) + .type(RRType.TXT) + .ttl(ttl); + List resourceRecords = new ArrayList<>(); + for (String value : values) { + ResourceRecord.Builder builder1 = ResourceRecord.builder(); + builder1.value(value); + resourceRecords.add(builder1.build()); + } + builder.resourceRecords(resourceRecords); + + Change.Builder builder2 = Change.builder(); + builder2.action(action); + builder2.resourceRecordSet(builder.build()); + return builder2.build(); + } + + // splits value into a list of quoted 255-character strings. + // only used in CREATE and UPSERT + private String splitTxt(String value) { + StringBuilder sb = new StringBuilder(); + while (value.length() > 253) { + sb.append(symbol).append(value, 0, 253).append(symbol); + value = value.substring(253); + } + if (value.length() > 0) { + sb.append(symbol).append(value).append(symbol); + } + return sb.toString(); + } + + public static boolean isSubdomain(String sub, String root) { + String subNoSuffix = postfix + StringUtils.strip(sub, postfix); + String rootNoSuffix = postfix + StringUtils.strip(root, postfix); + return subNoSuffix.endsWith(rootNoSuffix); + } + + public static class RecordSet { + + String[] values; + long ttl; + + public RecordSet(String[] values, long ttl) { + this.values = values; + this.ttl = ttl; + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/update/DnsType.java b/p2p/src/main/java/org/tron/p2p/dns/update/DnsType.java new file mode 100644 index 00000000000..ae935762d3d --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/update/DnsType.java @@ -0,0 +1,23 @@ +package org.tron.p2p.dns.update; + + +public enum DnsType { + AliYun(0, "aliyun dns server"), + AwsRoute53(1, "aws route53 server"); + + private final Integer value; + private final String desc; + + DnsType(Integer value, String desc) { + this.value = value; + this.desc = desc; + } + + public Integer getValue() { + return value; + } + + public String getDesc() { + return desc; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/update/Publish.java b/p2p/src/main/java/org/tron/p2p/dns/update/Publish.java new file mode 100644 index 00000000000..c5ccfe214b0 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/update/Publish.java @@ -0,0 +1,18 @@ +package org.tron.p2p.dns.update; + +import java.util.Map; +import org.tron.p2p.dns.tree.Tree; + +public interface Publish { + + int rootTTL = 10 * 60; + int treeNodeTTL = 7 * 24 * 60 * 60; + + void testConnect() throws Exception; + + void deploy(String domainName, Tree t) throws Exception; + + boolean deleteDomain(String domainName) throws Exception; + + Map collectRecords(String domainName) throws Exception; +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/update/PublishConfig.java b/p2p/src/main/java/org/tron/p2p/dns/update/PublishConfig.java new file mode 100644 index 00000000000..dbbf5b145ef --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/update/PublishConfig.java @@ -0,0 +1,24 @@ +package org.tron.p2p.dns.update; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; +import lombok.Data; + +@Data +public class PublishConfig { + + private boolean dnsPublishEnable = false; + private String dnsPrivate = null; + private List knownTreeUrls = new ArrayList<>(); + private List staticNodes = new ArrayList<>(); + private String dnsDomain = null; + private double changeThreshold = 0.1; + private int maxMergeSize = 5; + private DnsType dnsType = null; + private String accessKeyId = null; + private String accessKeySecret = null; + private String aliDnsEndpoint = null; //for aliYun + private String awsHostZoneId = null; //for aws + private String awsRegion = null; //for aws +} diff --git a/p2p/src/main/java/org/tron/p2p/dns/update/PublishService.java b/p2p/src/main/java/org/tron/p2p/dns/update/PublishService.java new file mode 100644 index 00000000000..e1b42b704fb --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/dns/update/PublishService.java @@ -0,0 +1,146 @@ +package org.tron.p2p.dns.update; + +import java.net.Inet4Address; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.NodeManager; +import org.tron.p2p.dns.DnsNode; +import org.tron.p2p.dns.tree.Tree; + +@Slf4j(topic = "net") +public class PublishService { + + private static final long publishDelay = 1 * 60 * 60; + + private ScheduledExecutorService publisher = Executors.newSingleThreadScheduledExecutor( + BasicThreadFactory.builder().namingPattern("publishService").build()); + private Publish publish; + + public void init() { + boolean supportV4 = Parameter.p2pConfig.getIp() != null; + PublishConfig publishConfig = Parameter.p2pConfig.getPublishConfig(); + if (checkConfig(supportV4, publishConfig)) { + try { + publish = getPublish(publishConfig); + publish.testConnect(); + } catch (Exception e) { + logger.error("Init PublishService failed", e); + return; + } + + if (publishConfig.getStaticNodes() != null && !publishConfig.getStaticNodes().isEmpty()) { + startPublish(); + } else { + publisher.scheduleWithFixedDelay(this::startPublish, 300, publishDelay, TimeUnit.SECONDS); + } + } + } + + private Publish getPublish(PublishConfig config) throws Exception { + Publish publish; + if (config.getDnsType() == DnsType.AliYun) { + publish = new AliClient(config.getAliDnsEndpoint(), + config.getAccessKeyId(), + config.getAccessKeySecret(), + config.getChangeThreshold()); + } else { + publish = new AwsClient(config.getAccessKeyId(), + config.getAccessKeySecret(), + config.getAwsHostZoneId(), + config.getAwsRegion(), + config.getChangeThreshold()); + } + return publish; + } + + private void startPublish() { + PublishConfig config = Parameter.p2pConfig.getPublishConfig(); + try { + Tree tree = new Tree(); + List nodes = getNodes(config); + tree.makeTree(1, nodes, config.getKnownTreeUrls(), config.getDnsPrivate()); + logger.info("Try to publish node count:{}", tree.getDnsNodes().size()); + publish.deploy(config.getDnsDomain(), tree); + } catch (Exception e) { + logger.error("Failed to publish dns", e); + } + } + + private List getNodes(PublishConfig config) throws UnknownHostException { + Set nodes = new HashSet<>(); + if (config.getStaticNodes() != null && !config.getStaticNodes().isEmpty()) { + for (InetSocketAddress staticAddress : config.getStaticNodes()) { + if (staticAddress.getAddress() instanceof Inet4Address) { + nodes.add(new Node(null, staticAddress.getAddress().getHostAddress(), null, + staticAddress.getPort())); + } else { + nodes.add(new Node(null, null, staticAddress.getAddress().getHostAddress(), + staticAddress.getPort())); + } + } + } else { + nodes.addAll(NodeManager.getConnectableNodes()); + nodes.add(NodeManager.getHomeNode()); + } + List dnsNodes = new ArrayList<>(); + for (Node node : nodes) { + DnsNode dnsNode = new DnsNode(node.getId(), node.getHostV4(), node.getHostV6(), + node.getPort()); + dnsNodes.add(dnsNode); + } + return Tree.merge(dnsNodes, config.getMaxMergeSize()); + } + + private boolean checkConfig(boolean supportV4, PublishConfig config) { + if (!config.isDnsPublishEnable()) { + logger.info("Dns publish service is disable"); + return false; + } + if (!supportV4) { + logger.error("Must have IP v4 connection to publish dns service"); + return false; + } + if (config.getDnsType() == null) { + logger.error( + "The dns server type must be specified when enabling the dns publishing service"); + return false; + } + if (StringUtils.isEmpty(config.getDnsDomain())) { + logger.error("The dns domain must be specified when enabling the dns publishing service"); + return false; + } + if (config.getDnsType() == DnsType.AliYun + && (StringUtils.isEmpty(config.getAccessKeyId()) + || StringUtils.isEmpty(config.getAccessKeySecret()) + || StringUtils.isEmpty(config.getAliDnsEndpoint()))) { + logger.error("The configuration items related to the Aliyun dns server cannot be empty"); + return false; + } + if (config.getDnsType() == DnsType.AwsRoute53 + && (StringUtils.isEmpty(config.getAccessKeyId()) + || StringUtils.isEmpty(config.getAccessKeySecret()) + || config.getAwsRegion() == null)) { + logger.error("The configuration items related to the AwsRoute53 dns server cannot be empty"); + return false; + } + return true; + } + + public void close() { + if (!publisher.isShutdown()) { + publisher.shutdown(); + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/example/StartApp.java b/p2p/src/main/java/org/tron/p2p/example/StartApp.java new file mode 100644 index 00000000000..175df0591da --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/example/StartApp.java @@ -0,0 +1,406 @@ +package org.tron.p2p.example; + +import static java.lang.Thread.sleep; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.apache.commons.lang3.StringUtils; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.P2pService; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.dns.update.DnsType; +import org.tron.p2p.dns.update.PublishConfig; +import org.tron.p2p.utils.ByteArray; +import org.tron.p2p.utils.NetUtil; + +@Slf4j(topic = "net") +public class StartApp { + + public static void main(String[] args) { + StartApp app = new StartApp(); + Parameter.version = 1; + + P2pService p2pService = new P2pService(); + long t1 = System.currentTimeMillis(); + Parameter.p2pConfig = new P2pConfig(); + logger.debug("P2pConfig cost {} ms", System.currentTimeMillis() - t1); + + CommandLine cli = null; + try { + cli = app.parseCli(args); + } catch (ParseException e) { + System.exit(0); + } + + if (cli.hasOption("s")) { + Parameter.p2pConfig.setSeedNodes(app.parseInetSocketAddressList(cli.getOptionValue("s"))); + logger.info("Seed nodes {}", Parameter.p2pConfig.getSeedNodes()); + } + + if (cli.hasOption("a")) { + Parameter.p2pConfig.setActiveNodes(app.parseInetSocketAddressList(cli.getOptionValue("a"))); + logger.info("Active nodes {}", Parameter.p2pConfig.getActiveNodes()); + } + + if (cli.hasOption("t")) { + // The option is declared as ip[,ip[...]]; resolving the whole comma- + // separated value as one hostname left every listed peer untrusted. + Parameter.p2pConfig.setTrustNodes(app.parseInetAddressList(cli.getOptionValue("t"))); + logger.info("Trust nodes {}", Parameter.p2pConfig.getTrustNodes()); + } + + if (cli.hasOption("M")) { + Parameter.p2pConfig.setMaxConnections(Integer.parseInt(cli.getOptionValue("M"))); + } + + if (cli.hasOption("m")) { + Parameter.p2pConfig.setMinConnections(Integer.parseInt(cli.getOptionValue("m"))); + } + + if (cli.hasOption("ma")) { + Parameter.p2pConfig.setMinActiveConnections(Integer.parseInt(cli.getOptionValue("ma"))); + } + + if (Parameter.p2pConfig.getMinConnections() > Parameter.p2pConfig.getMaxConnections()) { + logger.error("Check maxConnections({}) >= minConnections({}) failed", + Parameter.p2pConfig.getMaxConnections(), Parameter.p2pConfig.getMinConnections()); + System.exit(0); + } + + if (cli.hasOption("d")) { + int d = Integer.parseInt(cli.getOptionValue("d")); + if (d != 0 && d != 1) { + logger.error("Check discover failed, must be 0/1"); + System.exit(0); + } + Parameter.p2pConfig.setDiscoverEnable(d == 1); + } + + if (cli.hasOption("p")) { + Parameter.p2pConfig.setPort(Integer.parseInt(cli.getOptionValue("p"))); + } + + if (cli.hasOption("v")) { + Parameter.p2pConfig.setNetworkId(Integer.parseInt(cli.getOptionValue("v"))); + } + if (StringUtils.isNotEmpty(Parameter.p2pConfig.getIpv6())) { + logger.info("Local ipv6: {}", Parameter.p2pConfig.getIpv6()); + } + + app.checkDnsOption(cli); + + p2pService.start(Parameter.p2pConfig); + + while (true) { + try { + sleep(1000); + } catch (InterruptedException e) { + break; + } + } + } + + private CommandLine parseCli(String[] args) throws ParseException { + Options kadOptions = getKadOptions(); + Options dnsReadOptions = getDnsReadOption(); + Options dnsPublishOptions = getDnsPublishOption(); + + Options options = new Options(); + for (Option option : kadOptions.getOptions()) { + options.addOption(option); + } + for (Option option : dnsReadOptions.getOptions()) { + options.addOption(option); + } + for (Option option : dnsPublishOptions.getOptions()) { + options.addOption(option); + } + + CommandLine cli; + CommandLineParser cliParser = new DefaultParser(); + + try { + cli = cliParser.parse(options, args); + } catch (ParseException e) { + logger.error("Parse cli failed", e); + printHelpMessage(kadOptions, dnsReadOptions, dnsPublishOptions); + throw e; + } + + if (cli.hasOption("help")) { + printHelpMessage(kadOptions, dnsReadOptions, dnsPublishOptions); + System.exit(0); + } + return cli; + } + + private static final String configPublish = "publish"; + private static final String configDnsPrivate = "dns-private"; + private static final String configKnownUrls = "known-urls"; + private static final String configStaticNodes = "static-nodes"; + private static final String configDomain = "domain"; + private static final String configChangeThreshold = "change-threshold"; + private static final String configMaxMergeSize = "max-merge-size"; + private static final String configServerType = "server-type"; + private static final String configAccessId = "access-key-id"; + private static final String configAccessSecret = "access-key-secret"; + private static final String configHostZoneId = "host-zone-id"; + private static final String configAwsRegion = "aws-region"; + private static final String configAliEndPoint = "aliyun-dns-endpoint"; + + private void checkDnsOption(CommandLine cli) { + if (cli.hasOption("u")) { + Parameter.p2pConfig.setTreeUrls(Arrays.asList(cli.getOptionValue("u").split(","))); + } + + PublishConfig publishConfig = new PublishConfig(); + if (cli.hasOption(configPublish)) { + publishConfig.setDnsPublishEnable(true); + } + + if (publishConfig.isDnsPublishEnable()) { + if (cli.hasOption(configDnsPrivate)) { + String privateKey = cli.getOptionValue(configDnsPrivate); + if (privateKey.length() != 64) { + logger.error("Check {}, must be hex string of 64", configDnsPrivate); + System.exit(0); + } + try { + ByteArray.fromHexString(privateKey); + } catch (Exception ignore) { + logger.error("Check {}, must be hex string of 64", configDnsPrivate); + System.exit(0); + } + publishConfig.setDnsPrivate(privateKey); + } else { + logger.error("Check {}, must not be null", configDnsPrivate); + System.exit(0); + } + + if (cli.hasOption(configKnownUrls)) { + publishConfig.setKnownTreeUrls( + Arrays.asList(cli.getOptionValue(configKnownUrls).split(","))); + } + + if (cli.hasOption(configStaticNodes)) { + publishConfig.setStaticNodes( + parseInetSocketAddressList(cli.getOptionValue(configStaticNodes))); + } + + if (cli.hasOption(configDomain)) { + publishConfig.setDnsDomain(cli.getOptionValue(configDomain)); + } else { + logger.error("Check {}, must not be null", configDomain); + System.exit(0); + } + + if (cli.hasOption(configChangeThreshold)) { + double changeThreshold = Double.parseDouble(cli.getOptionValue(configChangeThreshold)); + if (changeThreshold >= 1.0) { + logger.error("Check {}, range between (0.0 ~ 1.0]", + configChangeThreshold); + } else { + publishConfig.setChangeThreshold(changeThreshold); + } + } + + if (cli.hasOption(configMaxMergeSize)) { + int maxMergeSize = Integer.parseInt(cli.getOptionValue(configMaxMergeSize)); + if (maxMergeSize > 5) { + logger.error("Check {}, range between [1 ~ 5]", configMaxMergeSize); + } else { + publishConfig.setMaxMergeSize(maxMergeSize); + } + } + + if (cli.hasOption(configServerType)) { + String serverType = cli.getOptionValue(configServerType); + if (!"aws".equalsIgnoreCase(serverType) && !"aliyun".equalsIgnoreCase(serverType)) { + logger.error("Check {}, must be aws or aliyun", configServerType); + System.exit(0); + } + if ("aws".equalsIgnoreCase(serverType)) { + publishConfig.setDnsType(DnsType.AwsRoute53); + } else { + publishConfig.setDnsType(DnsType.AliYun); + } + } else { + logger.error("Check {}, must not be null", configServerType); + System.exit(0); + } + + if (!cli.hasOption(configAccessId)) { + logger.error("Check {}, must not be null", configAccessId); + System.exit(0); + } else { + publishConfig.setAccessKeyId(cli.getOptionValue(configAccessId)); + } + + if (!cli.hasOption(configAccessSecret)) { + logger.error("Check {}, must not be null", configAccessSecret); + System.exit(0); + } else { + publishConfig.setAccessKeySecret(cli.getOptionValue(configAccessSecret)); + } + + if (publishConfig.getDnsType() == DnsType.AwsRoute53) { + // host-zone-id can be null + if (cli.hasOption(configHostZoneId)) { + publishConfig.setAwsHostZoneId(cli.getOptionValue(configHostZoneId)); + } + + if (!cli.hasOption(configAwsRegion)) { + logger.error("Check {}, must not be null", configAwsRegion); + System.exit(0); + } else { + String region = cli.getOptionValue(configAwsRegion); + publishConfig.setAwsRegion(region); + } + } else { + if (!cli.hasOption(configAliEndPoint)) { + logger.error("Check {}, must not be null", configAliEndPoint); + System.exit(0); + } else { + publishConfig.setAliDnsEndpoint(cli.getOptionValue(configAliEndPoint)); + } + } + } + Parameter.p2pConfig.setPublishConfig(publishConfig); + } + + private Options getKadOptions() { + + Option opt1 = new Option("s", "seed-nodes", true, + "seed node(s), required, ip:port[,ip:port[...]]"); + Option opt2 = new Option("t", "trust-ips", true, "trust ip(s), ip[,ip[...]]"); + Option opt3 = new Option("a", "active-nodes", true, "active node(s), ip:port[,ip:port[...]]"); + Option opt4 = new Option("M", "max-connection", true, "max connection number, int, default 50"); + Option opt5 = new Option("m", "min-connection", true, "min connection number, int, default 8"); + Option opt6 = new Option("d", "discover", true, "enable p2p discover, 0/1, default 1"); + Option opt7 = new Option("p", "port", true, "UDP & TCP port, int, default 18888"); + Option opt8 = new Option("v", "version", true, "p2p version, int, default 1"); + Option opt9 = new Option("ma", "min-active-connection", true, + "min active connection number, int, default 2"); + Option opt10 = new Option("h", "help", false, "print help message"); + + Options group = new Options(); + group.addOption(opt1); + group.addOption(opt2); + group.addOption(opt3); + group.addOption(opt4); + group.addOption(opt5); + group.addOption(opt6); + group.addOption(opt7); + group.addOption(opt8); + group.addOption(opt9); + group.addOption(opt10); + return group; + } + + private Options getDnsReadOption() { + Option opt = new Option("u", "url-schemes", true, + "dns url(s) to get nodes, url format tree://{pubkey}@{domain}, url[,url[...]]"); + Options group = new Options(); + group.addOption(opt); + return group; + } + + private Options getDnsPublishOption() { + Option opt1 = new Option(configPublish, configPublish, false, "enable dns publish"); + Option opt2 = new Option(null, configDnsPrivate, true, + "dns private key used to publish, required, hex string of length 64"); + Option opt3 = new Option(null, configKnownUrls, true, + "known dns urls to publish, url format tree://{pubkey}@{domain}, optional, url[,url[...]]"); + Option opt4 = new Option(null, configStaticNodes, true, + "static nodes to publish, if exist then nodes from kad will be ignored, " + + "optional, ip:port[,ip:port[...]]"); + Option opt5 = new Option(null, configDomain, true, + "dns domain to publish nodes, required, string"); + Option opt6 = new Option(null, configChangeThreshold, true, + "change threshold of add and delete to publish, optional, " + + "should be > 0 and < 1.0, default 0.1"); + Option opt7 = new Option(null, configMaxMergeSize, true, + "max merge size to merge node to a leaf node in dns tree, optional, " + + "should be [1~5], default 5"); + Option opt8 = new Option(null, configServerType, true, + "dns server to publish, required, only aws or aliyun is support"); + Option opt9 = new Option(null, configAccessId, true, + "access key id of aws or aliyun api, required, string"); + Option opt10 = new Option(null, configAccessSecret, true, + "access key secret of aws or aliyun api, required, string"); + Option opt11 = new Option(null, configAwsRegion, true, + "if server-type is aws, it's region of aws api, such as \"eu-south-1\", required, string"); + Option opt12 = new Option(null, configHostZoneId, true, + "if server-type is aws, it's host zone id of aws's domain, optional, string"); + Option opt13 = new Option(null, configAliEndPoint, true, + "if server-type is aliyun, it's endpoint of aws dns server, required, string"); + + Options group = new Options(); + group.addOption(opt1); + group.addOption(opt2); + group.addOption(opt3); + group.addOption(opt4); + group.addOption(opt5); + group.addOption(opt6); + group.addOption(opt7); + group.addOption(opt8); + group.addOption(opt9); + group.addOption(opt10); + group.addOption(opt11); + group.addOption(opt12); + group.addOption(opt13); + return group; + } + + private void printHelpMessage(Options kadOptions, Options dnsReadOptions, + Options dnsPublishOptions) { + HelpFormatter helpFormatter = new HelpFormatter(); + helpFormatter.printHelp("available p2p discovery cli options:", kadOptions); + helpFormatter.setSyntaxPrefix("\n"); + helpFormatter.printHelp("available dns read cli options:", dnsReadOptions); + helpFormatter.setSyntaxPrefix("\n"); + helpFormatter.printHelp("available dns publish cli options:", dnsPublishOptions); + helpFormatter.setSyntaxPrefix("\n"); + } + + // Package-private so StartAppArgsTest can pin the parsing, including the + // multi-address handling that --trust-ips used to get wrong. + List parseInetAddressList(String paras) { + List addresses = new ArrayList<>(); + for (String para : paras.split(",")) { + String host = para.trim(); + if (host.isEmpty()) { + continue; + } + InetAddress address = new InetSocketAddress(host, 0).getAddress(); + if (address != null) { + addresses.add(address); + } else { + logger.warn("Ignoring unresolvable trust ip {}", host); + } + } + return addresses; + } + + List parseInetSocketAddressList(String paras) { + List nodes = new ArrayList<>(); + for (String para : paras.split(",")) { + InetSocketAddress inetSocketAddress = NetUtil.parseInetSocketAddress(para); + if (inetSocketAddress != null) { + nodes.add(inetSocketAddress); + } + } + return nodes; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/exception/DnsException.java b/p2p/src/main/java/org/tron/p2p/exception/DnsException.java new file mode 100644 index 00000000000..40e4ff78d31 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/exception/DnsException.java @@ -0,0 +1,73 @@ +package org.tron.p2p.exception; + + +public class DnsException extends Exception { + + private static final long serialVersionUID = 9096335228978001485L; + private final DnsException.TypeEnum type; + + public DnsException(DnsException.TypeEnum type, String errMsg) { + super(type.desc + ", " + errMsg); + this.type = type; + } + + public DnsException(DnsException.TypeEnum type, Throwable throwable) { + super(throwable); + this.type = type; + } + + public DnsException(DnsException.TypeEnum type, String errMsg, Throwable throwable) { + super(errMsg, throwable); + this.type = type; + } + + public DnsException.TypeEnum getType() { + return type; + } + + public enum TypeEnum { + LOOK_UP_ROOT_FAILED(0, "look up root failed"), + //Resolver/sync errors + NO_ROOT_FOUND(1, "no valid root found"), + NO_ENTRY_FOUND(2, "no valid tree entry found"), + HASH_MISS_MATCH(3, "hash miss match"), + NODES_IN_LINK_TREE(4, "nodes entry in link tree"), + LINK_IN_NODES_TREE(5, "link entry in nodes tree"), + + // Entry parse errors + UNKNOWN_ENTRY(6, "unknown entry type"), + NO_PUBLIC_KEY(7, "missing public key"), + BAD_PUBLIC_KEY(8, "invalid public key"), + INVALID_NODES(9, "invalid node list"), + INVALID_CHILD(10, "invalid child hash"), + INVALID_SIGNATURE(11, "invalid base64 signature"), + INVALID_ROOT(12, "invalid DnsRoot proto"), + INVALID_SCHEME_URL(13, "invalid scheme url"), + + // Publish error + DEPLOY_DOMAIN_FAILED(14, "failed to deploy domain"), + + OTHER_ERROR(15, "other error"); + + private final Integer value; + private final String desc; + + TypeEnum(Integer value, String desc) { + this.value = value; + this.desc = desc; + } + + public Integer getValue() { + return value; + } + + public String getDesc() { + return desc; + } + + @Override + public String toString() { + return value + "-" + desc; + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/exception/P2pException.java b/p2p/src/main/java/org/tron/p2p/exception/P2pException.java new file mode 100644 index 00000000000..32191fb3af7 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/exception/P2pException.java @@ -0,0 +1,59 @@ +package org.tron.p2p.exception; + +public class P2pException extends Exception { + + private static final long serialVersionUID = 1390312274369330710L; + private final TypeEnum type; + + public P2pException(TypeEnum type, String errMsg) { + super(errMsg); + this.type = type; + } + + public P2pException(TypeEnum type, Throwable throwable) { + super(throwable); + this.type = type; + } + + public P2pException(TypeEnum type, String errMsg, Throwable throwable) { + super(errMsg, throwable); + this.type = type; + } + + public TypeEnum getType() { + return type; + } + + public enum TypeEnum { + NO_SUCH_MESSAGE(1, "no such message"), + PARSE_MESSAGE_FAILED(2, "parse message failed"), + MESSAGE_WITH_WRONG_LENGTH(3, "message with wrong length"), + BAD_MESSAGE(4, "bad message"), + BAD_PROTOCOL(5, "bad protocol"), + TYPE_ALREADY_REGISTERED(6, "type already registered"), + EMPTY_MESSAGE(7, "empty message"), + BIG_MESSAGE(8, "big message"); + + private final Integer value; + private final String desc; + + TypeEnum(Integer value, String desc) { + this.value = value; + this.desc = desc; + } + + public Integer getValue() { + return value; + } + + public String getDesc() { + return desc; + } + + @Override + public String toString() { + return value + ", " + desc; + } + } + +} diff --git a/p2p/src/main/java/org/tron/p2p/stats/P2pStats.java b/p2p/src/main/java/org/tron/p2p/stats/P2pStats.java new file mode 100644 index 00000000000..946c1404841 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/stats/P2pStats.java @@ -0,0 +1,15 @@ +package org.tron.p2p.stats; + +import lombok.Data; + +@Data +public class P2pStats { + private long tcpOutSize; + private long tcpInSize; + private long tcpOutPackets; + private long tcpInPackets; + private long udpOutSize; + private long udpInSize; + private long udpOutPackets; + private long udpInPackets; +} diff --git a/p2p/src/main/java/org/tron/p2p/stats/StatsManager.java b/p2p/src/main/java/org/tron/p2p/stats/StatsManager.java new file mode 100644 index 00000000000..83ea3ef7440 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/stats/StatsManager.java @@ -0,0 +1,17 @@ +package org.tron.p2p.stats; + +public class StatsManager { + + public P2pStats getP2pStats() { + P2pStats stats = new P2pStats(); + stats.setTcpInPackets(TrafficStats.tcp.getInPackets().get()); + stats.setTcpOutPackets(TrafficStats.tcp.getOutPackets().get()); + stats.setTcpInSize(TrafficStats.tcp.getInSize().get()); + stats.setTcpOutSize(TrafficStats.tcp.getOutSize().get()); + stats.setUdpInPackets(TrafficStats.udp.getInPackets().get()); + stats.setUdpOutPackets(TrafficStats.udp.getOutPackets().get()); + stats.setUdpInSize(TrafficStats.udp.getInSize().get()); + stats.setUdpOutSize(TrafficStats.udp.getOutSize().get()); + return stats; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/stats/TrafficStats.java b/p2p/src/main/java/org/tron/p2p/stats/TrafficStats.java new file mode 100644 index 00000000000..3badb172ba9 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/stats/TrafficStats.java @@ -0,0 +1,50 @@ +package org.tron.p2p.stats; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.channel.socket.DatagramPacket; +import java.util.concurrent.atomic.AtomicLong; +import lombok.Getter; + +public class TrafficStats { + public static final TrafficStatHandler tcp = new TrafficStatHandler(); + public static final TrafficStatHandler udp = new TrafficStatHandler(); + + @ChannelHandler.Sharable + static class TrafficStatHandler extends ChannelDuplexHandler { + @Getter + private AtomicLong outSize = new AtomicLong(); + @Getter + private AtomicLong inSize = new AtomicLong(); + @Getter + private AtomicLong outPackets = new AtomicLong(); + @Getter + private AtomicLong inPackets = new AtomicLong(); + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + inPackets.incrementAndGet(); + if (msg instanceof ByteBuf) { + inSize.addAndGet(((ByteBuf) msg).readableBytes()); + } else if (msg instanceof DatagramPacket) { + inSize.addAndGet(((DatagramPacket) msg).content().readableBytes()); + } + super.channelRead(ctx, msg); + } + + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) + throws Exception { + outPackets.incrementAndGet(); + if (msg instanceof ByteBuf) { + outSize.addAndGet(((ByteBuf) msg).readableBytes()); + } else if (msg instanceof DatagramPacket) { + outSize.addAndGet(((DatagramPacket) msg).content().readableBytes()); + } + super.write(ctx, msg, promise); + } + } +} diff --git a/p2p/src/main/java/org/tron/p2p/utils/ByteArray.java b/p2p/src/main/java/org/tron/p2p/utils/ByteArray.java new file mode 100644 index 00000000000..5d0102ee417 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/utils/ByteArray.java @@ -0,0 +1,193 @@ +package org.tron.p2p.utils; + +import com.google.common.primitives.Ints; +import com.google.common.primitives.Longs; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.bouncycastle.util.encoders.Hex; + + +/* + * Copyright (c) [2016] [ ] + * This file is part of the ethereumJ library. + * + * The ethereumJ library is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * The ethereumJ library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with the ethereumJ library. If not, see . + */ +@Slf4j(topic = "net") +public class ByteArray { + + public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; + public static final byte[] ZERO_BYTE_ARRAY = new byte[] {0}; + public static final int WORD_SIZE = 32; + + public static String toHexString(byte[] data) { + return data == null ? "" : Hex.toHexString(data); + } + + /** + * get bytes data from hex string data. + */ + public static byte[] fromHexString(String data) { + if (data == null) { + return EMPTY_BYTE_ARRAY; + } + if (data.startsWith("0x")) { + data = data.substring(2); + } + if (data.length() % 2 != 0) { + data = "0" + data; + } + return Hex.decode(data); + } + + /** + * get long data from bytes data. + */ + public static long toLong(byte[] b) { + return ArrayUtils.isEmpty(b) ? 0 : new BigInteger(1, b).longValue(); + } + + /** + * get int data from bytes data. + */ + public static int toInt(byte[] b) { + return ArrayUtils.isEmpty(b) ? 0 : new BigInteger(1, b).intValue(); + } + + /** + * get bytes data from string data. + */ + public static byte[] fromString(String s) { + return StringUtils.isBlank(s) ? null : s.getBytes(); + } + + /** + * get string data from bytes data. + */ + public static String toStr(byte[] b) { + return ArrayUtils.isEmpty(b) ? null : new String(b); + } + + public static byte[] fromLong(long val) { + return Longs.toByteArray(val); + } + + public static byte[] fromInt(int val) { + return Ints.toByteArray(val); + } + + /** + * get bytes data from object data. + */ + public static byte[] fromObject(Object obj) { + byte[] bytes = null; + try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) { + objectOutputStream.writeObject(obj); + objectOutputStream.flush(); + bytes = byteArrayOutputStream.toByteArray(); + } catch (IOException e) { + logger.error("Method objectToByteArray failed.", e); + } + return bytes; + } + + /** + * Stringify byte[] x + * null for null + * null for empty [] + */ + public static String toJsonHex(byte[] x) { + return x == null || x.length == 0 ? "0x" : "0x" + Hex.toHexString(x); + } + + + public static String toJsonHex(Long x) { + return x == null ? null : "0x" + Long.toHexString(x); + } + + public static String toJsonHex(int x) { + return toJsonHex((long) x); + } + + public static String toJsonHex(String x) { + return "0x" + x; + } + + public static BigInteger hexToBigInteger(String input) { + if (input.startsWith("0x")) { + return new BigInteger(input.substring(2), 16); + } else { + return new BigInteger(input, 10); + } + } + + + public static int jsonHexToInt(String x) throws Exception { + if (!x.startsWith("0x")) { + throw new Exception("Incorrect hex syntax"); + } + x = x.substring(2); + return Integer.parseInt(x, 16); + } + + /** + * Generate a subarray of a given byte array. + * + * @param input the input byte array + * @param start the start index + * @param end the end index + * @return a subarray of input, ranging from start (inclusively) to end + * (exclusively) + */ + public static byte[] subArray(byte[] input, int start, int end) { + byte[] result = new byte[end - start]; + System.arraycopy(input, start, result, 0, end - start); + return result; + } + + public static boolean isEmpty(byte[] input) { + return input == null || input.length == 0; + } + + public static boolean matrixContains(List source, byte[] obj) { + for (byte[] sobj : source) { + if (Arrays.equals(sobj, obj)) { + return true; + } + } + return false; + } + + public static String fromHex(String x) { + if (x.startsWith("0x")) { + x = x.substring(2); + } + if (x.length() % 2 != 0) { + x = "0" + x; + } + return x; + } + + public static int byte2int(byte b) { + return b & 0xFF; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/utils/CollectionUtils.java b/p2p/src/main/java/org/tron/p2p/utils/CollectionUtils.java new file mode 100644 index 00000000000..e5b5511210c --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/utils/CollectionUtils.java @@ -0,0 +1,22 @@ +package org.tron.p2p.utils; + +import java.util.ArrayList; +import java.util.List; + + +public class CollectionUtils { + + public static List truncate(List items, int limit) { + if (limit > items.size()) { + return new ArrayList<>(items); + } + List truncated = new ArrayList<>(limit); + for (T item : items) { + truncated.add(item); + if (truncated.size() == limit) { + break; + } + } + return truncated; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/utils/NetUtil.java b/p2p/src/main/java/org/tron/p2p/utils/NetUtil.java new file mode 100644 index 00000000000..f9aa43f5eb3 --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/utils/NetUtil.java @@ -0,0 +1,294 @@ +package org.tron.p2p.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.NetworkInterface; +import java.net.Socket; +import java.net.SocketException; +import java.net.URL; +import java.net.URLConnection; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.CompletionService; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.regex.Pattern; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.tron.p2p.base.Constant; +import org.tron.p2p.discover.Node; +import org.tron.p2p.protos.Discover; + +@Slf4j(topic = "net") +public class NetUtil { + + public static final Pattern PATTERN_IPv4 = + Pattern.compile("^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\" + + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\" + + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\" + + ".(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"); + + //https://codeantenna.com/a/jvrULhCbdj + public static final Pattern PATTERN_IPv6 = Pattern.compile( + "^((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa" + + "-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1" + + "-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|" + + "2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(" + + "([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5" + + "]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)" + + ")|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:(" + + "(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){" + + "3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4})" + + "{0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]" + + "?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f" + + "]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\" + + "d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:(" + + "(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){" + + "3}))|:)))(%\\S+)?$"); + + private static final String IPADDRESS_LOCALHOST = "127.0.0.1"; + + public static boolean validIpV4(String ip) { + if (StringUtils.isEmpty(ip)) { + return false; + } + return PATTERN_IPv4.matcher(ip).matches(); + } + + public static boolean validIpV6(String ip) { + if (StringUtils.isEmpty(ip)) { + return false; + } + return PATTERN_IPv6.matcher(ip).matches(); + } + + public static boolean validNode(Node node) { + if (node == null || node.getId() == null) { + return false; + } + if (node.getId().length != Constant.NODE_ID_LEN) { + return false; + } + if (StringUtils.isEmpty(node.getHostV4()) && StringUtils.isEmpty(node.getHostV6())) { + return false; + } + if (StringUtils.isNotEmpty(node.getHostV4()) && !validIpV4(node.getHostV4())) { + return false; + } + if (StringUtils.isNotEmpty(node.getHostV6()) && !validIpV6(node.getHostV6())) { + return false; + } + return true; + } + + public static Node getNode(Discover.Endpoint endpoint) { + return new Node(endpoint.getNodeId().toByteArray(), + ByteArray.toStr(endpoint.getAddress().toByteArray()), + ByteArray.toStr(endpoint.getAddressIpv6().toByteArray()), endpoint.getPort()); + } + + public static byte[] getNodeId() { + Random gen = new Random(); + byte[] id = new byte[Constant.NODE_ID_LEN]; + gen.nextBytes(id); + return id; + } + + private static String getExternalIp(String url, boolean isAskIpv4) { + BufferedReader in = null; + String ip = null; + try { + URLConnection urlConnection = new URL(url).openConnection(); + urlConnection.setConnectTimeout(10_000); //ms + urlConnection.setReadTimeout(10_000); //ms + in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); + ip = in.readLine(); + if (ip == null || ip.trim().isEmpty()) { + throw new IOException("Invalid address: " + ip); + } + InetAddress inetAddress = InetAddress.getByName(ip); + if (isAskIpv4 && !validIpV4(inetAddress.getHostAddress())) { + throw new IOException("Invalid address: " + ip); + } + if (!isAskIpv4 && !validIpV6(inetAddress.getHostAddress())) { + throw new IOException("Invalid address: " + ip); + } + return ip; + } catch (Exception e) { + logger.warn("Fail to get {} by {}, cause:{}", + Constant.ipV4Urls.contains(url) ? "ipv4" : "ipv6", url, e.getMessage()); + return null; + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + //ignore + } + } + } + } + + private static String getOuterIPv6Address() { + Enumeration networkInterfaces; + try { + networkInterfaces = NetworkInterface.getNetworkInterfaces(); + } catch (SocketException e) { + logger.warn("GetOuterIPv6Address failed", e); + return null; + } + while (networkInterfaces.hasMoreElements()) { + Enumeration inetAds = networkInterfaces.nextElement().getInetAddresses(); + while (inetAds.hasMoreElements()) { + InetAddress inetAddress = inetAds.nextElement(); + if (inetAddress instanceof Inet6Address && !isReservedAddress(inetAddress)) { + String ipAddress = inetAddress.getHostAddress(); + int index = ipAddress.indexOf('%'); + if (index > 0) { + ipAddress = ipAddress.substring(0, index); + } + return ipAddress; + } + } + } + return null; + } + + public static Set getAllLocalAddress() { + Set localIpSet = new HashSet<>(); + Enumeration networkInterfaces; + try { + networkInterfaces = NetworkInterface.getNetworkInterfaces(); + } catch (SocketException e) { + logger.warn("GetAllLocalAddress failed", e); + return localIpSet; + } + while (networkInterfaces.hasMoreElements()) { + Enumeration inetAds = networkInterfaces.nextElement().getInetAddresses(); + while (inetAds.hasMoreElements()) { + InetAddress inetAddress = inetAds.nextElement(); + String ipAddress = inetAddress.getHostAddress(); + int index = ipAddress.indexOf('%'); + if (index > 0) { + ipAddress = ipAddress.substring(0, index); + } + localIpSet.add(ipAddress); + } + } + return localIpSet; + } + + private static boolean isReservedAddress(InetAddress inetAddress) { + return inetAddress.isAnyLocalAddress() || inetAddress.isLinkLocalAddress() + || inetAddress.isLoopbackAddress() || inetAddress.isMulticastAddress(); + } + + public static String getExternalIpV4() { + long t1 = System.currentTimeMillis(); + String ipV4 = getIp(Constant.ipV4Urls, true); + logger.debug("GetExternalIpV4 cost {} ms", System.currentTimeMillis() - t1); + return ipV4; + } + + public static String getExternalIpV6() { + long t1 = System.currentTimeMillis(); + String ipV6 = getIp(Constant.ipV6Urls, false); + if (null == ipV6) { + ipV6 = getOuterIPv6Address(); + } + logger.debug("GetExternalIpV6 cost {} ms", System.currentTimeMillis() - t1); + return ipV6; + } + + public static InetSocketAddress parseInetSocketAddress(String para) { + int index = para.trim().lastIndexOf(":"); + if (index > 0) { + String host = para.substring(0, index); + if (host.startsWith("[") && host.endsWith("]")) { + host = host.substring(1, host.length() - 1); + } else { + if (host.contains(":")) { + throw new RuntimeException(String.format("Invalid inetSocketAddress: \"%s\", " + + "use ipv4:port or [ipv6]:port", para)); + } + } + int port = Integer.parseInt(para.substring(index + 1)); + return new InetSocketAddress(host, port); + } else { + throw new RuntimeException(String.format("Invalid inetSocketAddress: \"%s\", " + + "use ipv4:port or [ipv6]:port", para)); + } + } + + private static String getIp(List multiSrcUrls, boolean isAskIpv4) { + int threadSize = multiSrcUrls.size(); + ExecutorService executor = Executors.newFixedThreadPool(threadSize, + BasicThreadFactory.builder().namingPattern("getIp-%d").build()); + CompletionService completionService = new ExecutorCompletionService<>(executor); + + for (String url : multiSrcUrls) { + completionService.submit(() -> getExternalIp(url, isAskIpv4)); + } + + String ip = null; + for (int i = 0; i < threadSize; i++) { + try { + //block until any result return + Future f = completionService.take(); + String result = f.get(); + if (StringUtils.isNotEmpty(result)) { + ip = result; + break; + } + } catch (Exception ignored) { + //ignore + } + } + + executor.shutdownNow(); + return ip; + } + + public static String getLanIP() { + Enumeration networkInterfaces; + try { + networkInterfaces = NetworkInterface.getNetworkInterfaces(); + } catch (SocketException e) { + logger.warn("Can't get lan IP. Fall back to {}", IPADDRESS_LOCALHOST, e); + return IPADDRESS_LOCALHOST; + } + while (networkInterfaces.hasMoreElements()) { + NetworkInterface ni = networkInterfaces.nextElement(); + try { + if (!ni.isUp() || ni.isLoopback() || ni.isVirtual()) { + continue; + } + } catch (SocketException e) { + continue; + } + Enumeration inetAds = ni.getInetAddresses(); + while (inetAds.hasMoreElements()) { + InetAddress inetAddress = inetAds.nextElement(); + if (inetAddress instanceof Inet4Address && !isReservedAddress(inetAddress)) { + String ipAddress = inetAddress.getHostAddress(); + if (PATTERN_IPv4.matcher(ipAddress).find()) { + return ipAddress; + } + } + } + } + logger.warn("Can't get lan IP. Fall back to {}", IPADDRESS_LOCALHOST); + return IPADDRESS_LOCALHOST; + } +} diff --git a/p2p/src/main/java/org/tron/p2p/utils/ProtoUtil.java b/p2p/src/main/java/org/tron/p2p/utils/ProtoUtil.java new file mode 100644 index 00000000000..8ba64c88feb --- /dev/null +++ b/p2p/src/main/java/org/tron/p2p/utils/ProtoUtil.java @@ -0,0 +1,48 @@ +package org.tron.p2p.utils; + +import com.google.protobuf.ByteString; +import java.io.IOException; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.protos.Connect; +import org.xerial.snappy.Snappy; + +public class ProtoUtil { + + public static Connect.CompressMessage compressMessage(byte[] data) throws IOException { + Connect.CompressMessage.CompressType type = Connect.CompressMessage.CompressType.uncompress; + byte[] bytes = data; + + byte[] compressData = Snappy.compress(data); + if (compressData.length < bytes.length) { + type = Connect.CompressMessage.CompressType.snappy; + bytes = compressData; + } + + return Connect.CompressMessage.newBuilder() + .setData(ByteString.copyFrom(bytes)) + .setType(type).build(); + } + + public static byte[] uncompressMessage(Connect.CompressMessage message) + throws IOException, P2pException { + byte[] data = message.getData().toByteArray(); + if (message.getType().equals(Connect.CompressMessage.CompressType.uncompress)) { + return data; + } + + int length = Snappy.uncompressedLength(data); + if (length >= Parameter.MAX_MESSAGE_LENGTH) { + throw new P2pException(P2pException.TypeEnum.BIG_MESSAGE, + "message is too big, len=" + length); + } + + byte[] d2 = Snappy.uncompress(data); + if (d2.length >= Parameter.MAX_MESSAGE_LENGTH) { + throw new P2pException(P2pException.TypeEnum.BIG_MESSAGE, + "uncompressed is too big, len=" + length); + } + return d2; + } + +} diff --git a/p2p/src/main/java/org/web3j/crypto/ECDSASignature.java b/p2p/src/main/java/org/web3j/crypto/ECDSASignature.java new file mode 100644 index 00000000000..9d43a2155fe --- /dev/null +++ b/p2p/src/main/java/org/web3j/crypto/ECDSASignature.java @@ -0,0 +1,61 @@ +/* + * Copyright 2019 Web3 Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +package org.web3j.crypto; + +import java.math.BigInteger; + +/** An ECDSA Signature. */ +public class ECDSASignature { + public final BigInteger r; + public final BigInteger s; + + public ECDSASignature(BigInteger r, BigInteger s) { + this.r = r; + this.s = s; + } + + /** + * @return true if the S component is "low", that means it is below {@link Sign#HALF_CURVE_ORDER}. + * See + * BIP62. + */ + public boolean isCanonical() { + return s.compareTo(Sign.HALF_CURVE_ORDER) <= 0; + } + + /** + * Will automatically adjust the S component to be less than or equal to half the curve order, if + * necessary. This is required because for every signature (r,s) the signature (r, -s (mod N)) is + * a valid signature of the same message. However, we dislike the ability to modify the bits of a + * Bitcoin transaction after it's been signed, as that violates various assumed invariants. Thus + * in future only one of those forms will be considered legal and the other will be banned. + * + * @return the signature in a canonicalised form. + */ + public ECDSASignature toCanonicalised() { + if (!isCanonical()) { + // The order of the curve is the number of valid points that exist on that curve. + // If S is in the upper half of the number of valid points, then bring it back to + // the lower half. Otherwise, imagine that + // N = 10 + // s = 8, so (-8 % 10 == 2) thus both (r, 8) and (r, 2) are valid solutions. + // 10 - 8 == 2, giving us always the latter solution, which is canonical. + return new ECDSASignature(r, Sign.CURVE.getN().subtract(s)); + } else { + return this; + } + } +} diff --git a/p2p/src/main/java/org/web3j/crypto/ECKeyPair.java b/p2p/src/main/java/org/web3j/crypto/ECKeyPair.java new file mode 100644 index 00000000000..e637517943c --- /dev/null +++ b/p2p/src/main/java/org/web3j/crypto/ECKeyPair.java @@ -0,0 +1,112 @@ +/* + * Copyright 2019 Web3 Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +package org.web3j.crypto; + +import java.math.BigInteger; +import java.security.KeyPair; +import java.util.Arrays; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.params.ECPrivateKeyParameters; +import org.bouncycastle.crypto.signers.ECDSASigner; +import org.bouncycastle.crypto.signers.HMacDSAKCalculator; +import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey; +import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey; +import org.web3j.utils.Numeric; + +/** Elliptic Curve SECP-256k1 generated key pair. */ +public class ECKeyPair { + private final BigInteger privateKey; + private final BigInteger publicKey; + + public ECKeyPair(BigInteger privateKey, BigInteger publicKey) { + this.privateKey = privateKey; + this.publicKey = publicKey; + } + + public BigInteger getPrivateKey() { + return privateKey; + } + + public BigInteger getPublicKey() { + return publicKey; + } + + /** + * Sign a hash with the private key of this key pair. + * + * @param transactionHash the hash to sign + * @return An {@link ECDSASignature} of the hash + */ + public ECDSASignature sign(byte[] transactionHash) { + ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest())); + + ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKey, Sign.CURVE); + signer.init(true, privKey); + BigInteger[] components = signer.generateSignature(transactionHash); + + return new ECDSASignature(components[0], components[1]).toCanonicalised(); + } + + public static ECKeyPair create(KeyPair keyPair) { + BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate(); + BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic(); + + BigInteger privateKeyValue = privateKey.getD(); + + // Ethereum does not use encoded public keys like bitcoin - see + // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details + // Additionally, as the first bit is a constant prefix (0x04) we ignore this value + byte[] publicKeyBytes = publicKey.getQ().getEncoded(false); + BigInteger publicKeyValue = + new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length)); + + return new ECKeyPair(privateKeyValue, publicKeyValue); + } + + public static ECKeyPair create(BigInteger privateKey) { + return new ECKeyPair(privateKey, Sign.publicKeyFromPrivate(privateKey)); + } + + public static ECKeyPair create(byte[] privateKey) { + return create(Numeric.toBigInt(privateKey)); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + ECKeyPair ecKeyPair = (ECKeyPair) o; + + if (privateKey != null + ? !privateKey.equals(ecKeyPair.privateKey) + : ecKeyPair.privateKey != null) { + return false; + } + + return publicKey != null ? publicKey.equals(ecKeyPair.publicKey) : ecKeyPair.publicKey == null; + } + + @Override + public int hashCode() { + int result = privateKey != null ? privateKey.hashCode() : 0; + result = 31 * result + (publicKey != null ? publicKey.hashCode() : 0); + return result; + } +} diff --git a/p2p/src/main/java/org/web3j/crypto/Hash.java b/p2p/src/main/java/org/web3j/crypto/Hash.java new file mode 100644 index 00000000000..ac27c4eee2c --- /dev/null +++ b/p2p/src/main/java/org/web3j/crypto/Hash.java @@ -0,0 +1,139 @@ +/* + * Copyright 2019 Web3 Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +package org.web3j.crypto; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Locale; +import org.bouncycastle.crypto.digests.RIPEMD160Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; +import org.bouncycastle.crypto.macs.HMac; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.jcajce.provider.digest.Blake2b; +import org.bouncycastle.jcajce.provider.digest.Keccak; +import org.web3j.utils.Numeric; + +/** Cryptographic hash functions. */ +public class Hash { + private Hash() {} + + /** + * Generates a digest for the given {@code input}. + * + * @param input The input to digest + * @param algorithm The hash algorithm to use + * @return The hash value for the given input + * @throws RuntimeException If we couldn't find any provider for the given algorithm + */ + public static byte[] hash(byte[] input, String algorithm) { + try { + MessageDigest digest = MessageDigest.getInstance(algorithm.toUpperCase(Locale.ROOT)); + return digest.digest(input); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("Couldn't find a " + algorithm + " provider", e); + } + } + + /** + * Keccak-256 hash function. + * + * @param hexInput hex encoded input data with optional 0x prefix + * @return hash value as hex encoded string + */ + public static String sha3(String hexInput) { + byte[] bytes = Numeric.hexStringToByteArray(hexInput); + byte[] result = sha3(bytes); + return Numeric.toHexString(result); + } + + /** + * Keccak-256 hash function. + * + * @param input binary encoded input data + * @param offset of start of data + * @param length of data + * @return hash value + */ + public static byte[] sha3(byte[] input, int offset, int length) { + Keccak.DigestKeccak kecc = new Keccak.Digest256(); + kecc.update(input, offset, length); + return kecc.digest(); + } + + /** + * Keccak-256 hash function. + * + * @param input binary encoded input data + * @return hash value + */ + public static byte[] sha3(byte[] input) { + return sha3(input, 0, input.length); + } + + /** + * Keccak-256 hash function that operates on a UTF-8 encoded String. + * + * @param utf8String UTF-8 encoded string + * @return hash value as hex encoded string + */ + public static String sha3String(String utf8String) { + return Numeric.toHexString(sha3(utf8String.getBytes(StandardCharsets.UTF_8))); + } + + /** + * Generates SHA-256 digest for the given {@code input}. + * + * @param input The input to digest + * @return The hash value for the given input + * @throws RuntimeException If we couldn't find any SHA-256 provider + */ + public static byte[] sha256(byte[] input) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + return digest.digest(input); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("Couldn't find a SHA-256 provider", e); + } + } + + public static byte[] hmacSha512(byte[] key, byte[] input) { + HMac hMac = new HMac(new SHA512Digest()); + hMac.init(new KeyParameter(key)); + hMac.update(input, 0, input.length); + byte[] out = new byte[64]; + hMac.doFinal(out, 0); + return out; + } + + public static byte[] sha256hash160(byte[] input) { + byte[] sha256 = sha256(input); + RIPEMD160Digest digest = new RIPEMD160Digest(); + digest.update(sha256, 0, sha256.length); + byte[] out = new byte[20]; + digest.doFinal(out, 0); + return out; + } + + /** + * Blake2-256 hash function. + * + * @param input binary encoded input data + * @return hash value + */ + public static byte[] blake2b256(byte[] input) { + return new Blake2b.Blake2b256().digest(input); + } +} diff --git a/p2p/src/main/java/org/web3j/crypto/Sign.java b/p2p/src/main/java/org/web3j/crypto/Sign.java new file mode 100644 index 00000000000..629e694d585 --- /dev/null +++ b/p2p/src/main/java/org/web3j/crypto/Sign.java @@ -0,0 +1,356 @@ +/* + * Copyright 2019 Web3 Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +package org.web3j.crypto; + +import static org.web3j.utils.Assertions.verifyPrecondition; + +import java.math.BigInteger; +import java.security.SignatureException; +import java.util.Arrays; +import org.bouncycastle.asn1.x9.X9ECParameters; +import org.bouncycastle.asn1.x9.X9IntegerConverter; +import org.bouncycastle.crypto.ec.CustomNamedCurves; +import org.bouncycastle.crypto.params.ECDomainParameters; +import org.bouncycastle.math.ec.ECAlgorithms; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.math.ec.FixedPointCombMultiplier; +import org.bouncycastle.math.ec.custom.sec.SecP256K1Curve; +import org.web3j.utils.Numeric; + +/** + * Transaction signing logic. + * + *

    Adapted from the + * BitcoinJ ECKey implementation. + */ +public class Sign { + + public static final X9ECParameters CURVE_PARAMS = CustomNamedCurves.getByName("secp256k1"); + static final ECDomainParameters CURVE = + new ECDomainParameters( + CURVE_PARAMS.getCurve(), CURVE_PARAMS.getG(), CURVE_PARAMS.getN(), CURVE_PARAMS.getH()); + static final BigInteger HALF_CURVE_ORDER = CURVE_PARAMS.getN().shiftRight(1); + + static final String MESSAGE_PREFIX = "\u0019Ethereum Signed Message:\n"; + + static byte[] getEthereumMessagePrefix(int messageLength) { + return MESSAGE_PREFIX.concat(String.valueOf(messageLength)).getBytes(); + } + + static byte[] getEthereumMessageHash(byte[] message) { + byte[] prefix = getEthereumMessagePrefix(message.length); + + byte[] result = new byte[prefix.length + message.length]; + System.arraycopy(prefix, 0, result, 0, prefix.length); + System.arraycopy(message, 0, result, prefix.length, message.length); + + return Hash.sha3(result); + } + + public static SignatureData signPrefixedMessage(byte[] message, ECKeyPair keyPair) { + return signMessage(getEthereumMessageHash(message), keyPair, false); + } + + public static SignatureData signMessage(byte[] message, ECKeyPair keyPair) { + return signMessage(message, keyPair, true); + } + + public static SignatureData signMessage(byte[] message, ECKeyPair keyPair, boolean needToHash) { + BigInteger publicKey = keyPair.getPublicKey(); + byte[] messageHash; + if (needToHash) { + messageHash = Hash.sha3(message); + } else { + messageHash = message; + } + + ECDSASignature sig = keyPair.sign(messageHash); + // Now we have to work backwards to figure out the recId needed to recover the signature. + int recId = -1; + for (int i = 0; i < 4; i++) { + BigInteger k = recoverFromSignature(i, sig, messageHash); + if (k != null && k.equals(publicKey)) { + recId = i; + break; + } + } + if (recId == -1) { + throw new RuntimeException( + "Could not construct a recoverable key. Are your credentials valid?"); + } + + int headerByte = recId + 27; + + // 1 header + 32 bytes for R + 32 bytes for S + byte[] v = new byte[] {(byte) headerByte}; + byte[] r = Numeric.toBytesPadded(sig.r, 32); + byte[] s = Numeric.toBytesPadded(sig.s, 32); + + return new SignatureData(v, r, s); + } + + /** + * Given the components of a signature and a selector value, recover and return the public key + * that generated the signature according to the algorithm in SEC1v2 section 4.1.6. + * + *

    The recId is an index from 0 to 3 which indicates which of the 4 possible keys is the + * correct one. Because the key recovery operation yields multiple potential keys, the correct key + * must either be stored alongside the signature, or you must be willing to try each recId in turn + * until you find one that outputs the key you are expecting. + * + *

    If this method returns null it means recovery was not possible and recId should be iterated. + * + *

    Given the above two points, a correct usage of this method is inside a for loop from 0 to 3, + * and if the output is null OR a key that is not the one you expect, you try again with the next + * recId. + * + * @param recId Which possible key to recover. + * @param sig the R and S components of the signature, wrapped. + * @param message Hash of the data that was signed. + * @return An ECKey containing only the public part, or null if recovery wasn't possible. + */ + public static BigInteger recoverFromSignature(int recId, ECDSASignature sig, byte[] message) { + verifyPrecondition(recId >= 0, "recId must be positive"); + verifyPrecondition(sig.r.signum() >= 0, "r must be positive"); + verifyPrecondition(sig.s.signum() >= 0, "s must be positive"); + verifyPrecondition(message != null, "message cannot be null"); + + // 1.0 For j from 0 to h (h == recId here and the loop is outside this function) + // 1.1 Let x = r + jn + BigInteger n = CURVE.getN(); // Curve order. + BigInteger i = BigInteger.valueOf((long) recId / 2); + BigInteger x = sig.r.add(i.multiply(n)); + // 1.2. Convert the integer x to an octet string X of length mlen using the conversion + // routine specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉. + // 1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve point R + // using the conversion routine specified in Section 2.3.4. If this conversion + // routine outputs "invalid", then do another iteration of Step 1. + // + // More concisely, what these points mean is to use X as a compressed public key. + BigInteger prime = SecP256K1Curve.q; + if (x.compareTo(prime) >= 0) { + // Cannot have point co-ordinates larger than this as everything takes place modulo Q. + return null; + } + // Compressed keys require you to know an extra bit of data about the y-coord as there are + // two possibilities. So it's encoded in the recId. + ECPoint R = decompressKey(x, (recId & 1) == 1); + // 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers + // responsibility). + if (!R.multiply(n).isInfinity()) { + return null; + } + // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification. + BigInteger e = new BigInteger(1, message); + // 1.6. For k from 1 to 2 do the following. (loop is outside this function via + // iterating recId) + // 1.6.1. Compute a candidate public key as: + // Q = mi(r) * (sR - eG) + // + // Where mi(x) is the modular multiplicative inverse. We transform this into the following: + // Q = (mi(r) * s ** R) + (mi(r) * -e ** G) + // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n). + // In the above equation ** is point multiplication and + is point addition (the EC group + // operator). + // + // We can find the additive inverse by subtracting e from zero then taking the mod. For + // example the additive inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and + // -3 mod 11 = 8. + BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n); + BigInteger rInv = sig.r.modInverse(n); + BigInteger srInv = rInv.multiply(sig.s).mod(n); + BigInteger eInvrInv = rInv.multiply(eInv).mod(n); + ECPoint q = ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv); + + byte[] qBytes = q.getEncoded(false); + // We remove the prefix + return new BigInteger(1, Arrays.copyOfRange(qBytes, 1, qBytes.length)); + } + + /** Decompress a compressed public key (x co-ord and low-bit of y-coord). */ + private static ECPoint decompressKey(BigInteger xBN, boolean yBit) { + X9IntegerConverter x9 = new X9IntegerConverter(); + byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve())); + compEnc[0] = (byte) (yBit ? 0x03 : 0x02); + return CURVE.getCurve().decodePoint(compEnc); + } + + /** + * Given an arbitrary piece of text and an Ethereum message signature encoded in bytes, returns + * the public key that was used to sign it. This can then be compared to the expected public key + * to determine if the signature was correct. + * + * @param message RLP encoded message. + * @param signatureData The message signature components + * @return the public key used to sign the message + * @throws SignatureException If the public key could not be recovered or if there was a signature + * format error. + */ + public static BigInteger signedMessageToKey(byte[] message, SignatureData signatureData) + throws SignatureException { + return signedMessageHashToKey(Hash.sha3(message), signatureData); + } + + /** + * Given an arbitrary message and an Ethereum message signature encoded in bytes, returns the + * public key that was used to sign it. This can then be compared to the expected public key to + * determine if the signature was correct. + * + * @param message The message. + * @param signatureData The message signature components + * @return the public key used to sign the message + * @throws SignatureException If the public key could not be recovered or if there was a signature + * format error. + */ + public static BigInteger signedPrefixedMessageToKey(byte[] message, SignatureData signatureData) + throws SignatureException { + return signedMessageHashToKey(getEthereumMessageHash(message), signatureData); + } + + /** + * Given an arbitrary message hash and an Ethereum message signature encoded in bytes, returns the + * public key that was used to sign it. This can then be compared to the expected public key to + * determine if the signature was correct. + * + * @param messageHash The message hash. + * @param signatureData The message signature components + * @return the public key used to sign the message + * @throws SignatureException If the public key could not be recovered or if there was a signature + * format error. + */ + public static BigInteger signedMessageHashToKey(byte[] messageHash, SignatureData signatureData) + throws SignatureException { + + byte[] r = signatureData.getR(); + byte[] s = signatureData.getS(); + verifyPrecondition(r != null && r.length == 32, "r must be 32 bytes"); + verifyPrecondition(s != null && s.length == 32, "s must be 32 bytes"); + + int header = signatureData.getV()[0] & 0xFF; + // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, + // 0x1D = second key with even y, 0x1E = second key with odd y + if (header < 27 || header > 34) { + throw new SignatureException("Header byte out of range: " + header); + } + + ECDSASignature sig = + new ECDSASignature( + new BigInteger(1, signatureData.getR()), new BigInteger(1, signatureData.getS())); + + int recId = header - 27; + BigInteger key = recoverFromSignature(recId, sig, messageHash); + if (key == null) { + throw new SignatureException("Could not recover public key from signature"); + } + return key; + } + + /** + * Returns public key from the given private key. + * + * @param privKey the private key to derive the public key from + * @return BigInteger encoded public key + */ + public static BigInteger publicKeyFromPrivate(BigInteger privKey) { + ECPoint point = publicPointFromPrivate(privKey); + + byte[] encoded = point.getEncoded(false); + return new BigInteger(1, Arrays.copyOfRange(encoded, 1, encoded.length)); // remove prefix + } + + /** + * Returns public key point from the given private key. + * + * @param privKey the private key to derive the public key from + * @return ECPoint public key + */ + public static ECPoint publicPointFromPrivate(BigInteger privKey) { + /* + * TODO: FixedPointCombMultiplier currently doesn't support scalars longer than the group + * order, but that could change in future versions. + */ + if (privKey.bitLength() > CURVE.getN().bitLength()) { + privKey = privKey.mod(CURVE.getN()); + } + return new FixedPointCombMultiplier().multiply(CURVE.getG(), privKey); + } + + /** + * Returns public key point from the given curve. + * + * @param bits representing the point on the curve + * @return BigInteger encoded public key + */ + public static BigInteger publicFromPoint(byte[] bits) { + return new BigInteger(1, Arrays.copyOfRange(bits, 1, bits.length)); // remove prefix + } + + public static class SignatureData { + private final byte[] v; + private final byte[] r; + private final byte[] s; + + public SignatureData(byte v, byte[] r, byte[] s) { + this(new byte[] {v}, r, s); + } + + public SignatureData(byte[] v, byte[] r, byte[] s) { + this.v = v; + this.r = r; + this.s = s; + } + + public byte[] getV() { + return v; + } + + public byte[] getR() { + return r; + } + + public byte[] getS() { + return s; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + SignatureData that = (SignatureData) o; + + if (!Arrays.equals(v, that.v)) { + return false; + } + if (!Arrays.equals(r, that.r)) { + return false; + } + return Arrays.equals(s, that.s); + } + + @Override + public int hashCode() { + int result = Arrays.hashCode(v); + result = 31 * result + Arrays.hashCode(r); + result = 31 * result + Arrays.hashCode(s); + return result; + } + } +} diff --git a/p2p/src/main/java/org/web3j/exceptions/MessageDecodingException.java b/p2p/src/main/java/org/web3j/exceptions/MessageDecodingException.java new file mode 100644 index 00000000000..7acdae74470 --- /dev/null +++ b/p2p/src/main/java/org/web3j/exceptions/MessageDecodingException.java @@ -0,0 +1,26 @@ +/* + * Copyright 2019 Web3 Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +package org.web3j.exceptions; + +/** Encoding exception. */ +public class MessageDecodingException extends RuntimeException { + public MessageDecodingException(String message) { + super(message); + } + + public MessageDecodingException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/p2p/src/main/java/org/web3j/exceptions/MessageEncodingException.java b/p2p/src/main/java/org/web3j/exceptions/MessageEncodingException.java new file mode 100644 index 00000000000..2230d5d1175 --- /dev/null +++ b/p2p/src/main/java/org/web3j/exceptions/MessageEncodingException.java @@ -0,0 +1,26 @@ +/* + * Copyright 2019 Web3 Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +package org.web3j.exceptions; + +/** Encoding exception. */ +public class MessageEncodingException extends RuntimeException { + public MessageEncodingException(String message) { + super(message); + } + + public MessageEncodingException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/p2p/src/main/java/org/web3j/utils/Assertions.java b/p2p/src/main/java/org/web3j/utils/Assertions.java new file mode 100644 index 00000000000..19db0256835 --- /dev/null +++ b/p2p/src/main/java/org/web3j/utils/Assertions.java @@ -0,0 +1,31 @@ +/* + * Copyright 2019 Web3 Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +package org.web3j.utils; + +/** Assertion utility functions. */ +public class Assertions { + + /** + * Verify that the provided precondition holds true. + * + * @param assertionResult assertion value + * @param errorMessage error message if precondition failure + */ + public static void verifyPrecondition(boolean assertionResult, String errorMessage) { + if (!assertionResult) { + throw new RuntimeException(errorMessage); + } + } +} diff --git a/p2p/src/main/java/org/web3j/utils/Numeric.java b/p2p/src/main/java/org/web3j/utils/Numeric.java new file mode 100644 index 00000000000..eee4ad3d50b --- /dev/null +++ b/p2p/src/main/java/org/web3j/utils/Numeric.java @@ -0,0 +1,252 @@ +/* + * Copyright 2019 Web3 Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +package org.web3j.utils; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Arrays; +import org.web3j.exceptions.MessageDecodingException; +import org.web3j.exceptions.MessageEncodingException; + +/** + * Message codec functions. + * + *

    Implementation as per https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding + */ +public final class Numeric { + + private static final String HEX_PREFIX = "0x"; + + private Numeric() {} + + public static String encodeQuantity(BigInteger value) { + if (value.signum() != -1) { + return HEX_PREFIX + value.toString(16); + } else { + throw new MessageEncodingException("Negative values are not supported"); + } + } + + public static BigInteger decodeQuantity(String value) { + if (isLongValue(value)) { + return BigInteger.valueOf(Long.parseLong(value)); + } + + if (!isValidHexQuantity(value)) { + throw new MessageDecodingException("Value must be in format 0x[1-9]+[0-9]* or 0x0"); + } + try { + return new BigInteger(value.substring(2), 16); + } catch (NumberFormatException e) { + throw new MessageDecodingException("Negative ", e); + } + } + + private static boolean isLongValue(String value) { + try { + Long.parseLong(value); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + private static boolean isValidHexQuantity(String value) { + if (value == null) { + return false; + } + + if (value.length() < 3) { + return false; + } + + if (!value.startsWith(HEX_PREFIX)) { + return false; + } + + // If TestRpc resolves the following issue, we can reinstate this code + // https://github.com/ethereumjs/testrpc/issues/220 + // if (value.length() > 3 && value.charAt(2) == '0') { + // return false; + // } + + return true; + } + + public static String cleanHexPrefix(String input) { + if (containsHexPrefix(input)) { + return input.substring(2); + } else { + return input; + } + } + + public static String prependHexPrefix(String input) { + if (!containsHexPrefix(input)) { + return HEX_PREFIX + input; + } else { + return input; + } + } + + public static boolean containsHexPrefix(String input) { + return !Strings.isEmpty(input) + && input.length() > 1 + && input.charAt(0) == '0' + && input.charAt(1) == 'x'; + } + + public static BigInteger toBigInt(byte[] value, int offset, int length) { + return toBigInt((Arrays.copyOfRange(value, offset, offset + length))); + } + + public static BigInteger toBigInt(byte[] value) { + return new BigInteger(1, value); + } + + public static BigInteger toBigInt(String hexValue) { + String cleanValue = cleanHexPrefix(hexValue); + return toBigIntNoPrefix(cleanValue); + } + + public static BigInteger toBigIntNoPrefix(String hexValue) { + return new BigInteger(hexValue, 16); + } + + public static String toHexStringWithPrefix(BigInteger value) { + return HEX_PREFIX + value.toString(16); + } + + public static String toHexStringNoPrefix(BigInteger value) { + return value.toString(16); + } + + public static String toHexStringNoPrefix(byte[] input) { + return toHexString(input, 0, input.length, false); + } + + public static String toHexStringWithPrefixZeroPadded(BigInteger value, int size) { + return toHexStringZeroPadded(value, size, true); + } + + public static String toHexStringWithPrefixSafe(BigInteger value) { + String result = toHexStringNoPrefix(value); + if (result.length() < 2) { + result = Strings.zeros(1) + result; + } + return HEX_PREFIX + result; + } + + public static String toHexStringNoPrefixZeroPadded(BigInteger value, int size) { + return toHexStringZeroPadded(value, size, false); + } + + private static String toHexStringZeroPadded(BigInteger value, int size, boolean withPrefix) { + String result = toHexStringNoPrefix(value); + + int length = result.length(); + if (length > size) { + throw new UnsupportedOperationException("Value " + result + "is larger then length " + size); + } else if (value.signum() < 0) { + throw new UnsupportedOperationException("Value cannot be negative"); + } + + if (length < size) { + result = Strings.zeros(size - length) + result; + } + + if (withPrefix) { + return HEX_PREFIX + result; + } else { + return result; + } + } + + public static byte[] toBytesPadded(BigInteger value, int length) { + byte[] result = new byte[length]; + byte[] bytes = value.toByteArray(); + + int bytesLength; + int srcOffset; + if (bytes[0] == 0) { + bytesLength = bytes.length - 1; + srcOffset = 1; + } else { + bytesLength = bytes.length; + srcOffset = 0; + } + + if (bytesLength > length) { + throw new RuntimeException("Input is too large to put in byte array of size " + length); + } + + int destOffset = length - bytesLength; + System.arraycopy(bytes, srcOffset, result, destOffset, bytesLength); + return result; + } + + public static byte[] hexStringToByteArray(String input) { + String cleanInput = cleanHexPrefix(input); + + int len = cleanInput.length(); + + if (len == 0) { + return new byte[] {}; + } + + byte[] data; + int startIdx; + if (len % 2 != 0) { + data = new byte[(len / 2) + 1]; + data[0] = (byte) Character.digit(cleanInput.charAt(0), 16); + startIdx = 1; + } else { + data = new byte[len / 2]; + startIdx = 0; + } + + for (int i = startIdx; i < len; i += 2) { + data[(i + 1) / 2] = + (byte) + ((Character.digit(cleanInput.charAt(i), 16) << 4) + + Character.digit(cleanInput.charAt(i + 1), 16)); + } + return data; + } + + public static String toHexString(byte[] input, int offset, int length, boolean withPrefix) { + StringBuilder stringBuilder = new StringBuilder(); + if (withPrefix) { + stringBuilder.append("0x"); + } + for (int i = offset; i < offset + length; i++) { + stringBuilder.append(String.format("%02x", input[i] & 0xFF)); + } + + return stringBuilder.toString(); + } + + public static String toHexString(byte[] input) { + return toHexString(input, 0, input.length, true); + } + + public static byte asByte(int m, int n) { + return (byte) ((m << 4) | n); + } + + public static boolean isIntegerValue(BigDecimal value) { + return value.signum() == 0 || value.scale() <= 0 || value.stripTrailingZeros().scale() <= 0; + } +} diff --git a/p2p/src/main/java/org/web3j/utils/Strings.java b/p2p/src/main/java/org/web3j/utils/Strings.java new file mode 100644 index 00000000000..87e5374f9a4 --- /dev/null +++ b/p2p/src/main/java/org/web3j/utils/Strings.java @@ -0,0 +1,61 @@ +/* + * Copyright 2019 Web3 Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +package org.web3j.utils; + +import java.util.List; +import java.util.Locale; + +/** String utility functions. */ +public class Strings { + + private Strings() {} + + public static String toCsv(List src) { + // return src == null ? null : String.join(", ", src.toArray(new String[0])); + return join(src, ", "); + } + + public static String join(List src, String delimiter) { + return src == null ? null : String.join(delimiter, src.toArray(new String[0])); + } + + public static String capitaliseFirstLetter(String string) { + if (string == null || string.length() == 0) { + return string; + } else { + return string.substring(0, 1).toUpperCase(Locale.ROOT) + string.substring(1); + } + } + + public static String lowercaseFirstLetter(String string) { + if (string == null || string.length() == 0) { + return string; + } else { + return string.substring(0, 1).toLowerCase(Locale.ROOT) + string.substring(1); + } + } + + public static String zeros(int n) { + return repeat('0', n); + } + + public static String repeat(char value, int n) { + return new String(new char[n]).replace("\0", String.valueOf(value)); + } + + public static boolean isEmpty(String s) { + return s == null || s.length() == 0; + } +} diff --git a/p2p/src/main/proto/Connect.proto b/p2p/src/main/proto/Connect.proto new file mode 100644 index 00000000000..d03d123a963 --- /dev/null +++ b/p2p/src/main/proto/Connect.proto @@ -0,0 +1,60 @@ +syntax = "proto3"; + +import "Discover.proto"; + +option java_package = "org.tron.p2p.protos"; +option java_outer_classname = "Connect"; + +message KeepAliveMessage { + int64 timestamp = 1; +} + +message HelloMessage { + Endpoint from = 1; + int32 network_id = 2; + int32 code = 3; + int64 timestamp = 4; + int32 version = 5; +} + +message StatusMessage { + Endpoint from = 1; + int32 version = 2; + int32 network_id = 3; + int32 maxConnections = 4; + int32 currentConnections = 5; + int64 timestamp = 6; +} + +message CompressMessage { + enum CompressType { + uncompress = 0; + snappy = 1; + } + + CompressType type = 1; + bytes data = 2; +} + +enum DisconnectReason { + PEER_QUITING = 0x00; + BAD_PROTOCOL = 0x01; + TOO_MANY_PEERS = 0x02; + DUPLICATE_PEER = 0x03; + DIFFERENT_VERSION = 0x04; + RANDOM_ELIMINATION = 0x05; + EMPTY_MESSAGE = 0X06; + PING_TIMEOUT = 0x07; + DISCOVER_MODE = 0x08; + //DETECT_COMPLETE = 0x09; + NO_SUCH_MESSAGE = 0x0A; + BAD_MESSAGE = 0x0B; + TOO_MANY_PEERS_WITH_SAME_IP = 0x0C; + RECENT_DISCONNECT = 0x0D; + DUP_HANDSHAKE = 0x0E; + UNKNOWN = 0xFF; +} + +message P2pDisconnectMessage { + DisconnectReason reason = 1; +} \ No newline at end of file diff --git a/p2p/src/main/proto/Discover.proto b/p2p/src/main/proto/Discover.proto new file mode 100644 index 00000000000..8a53761115c --- /dev/null +++ b/p2p/src/main/proto/Discover.proto @@ -0,0 +1,50 @@ +syntax = "proto3"; + +option java_package = "org.tron.p2p.protos"; +option java_outer_classname = "Discover"; + +message Endpoint { + bytes address = 1; + int32 port = 2; + bytes nodeId = 3; + bytes addressIpv6 = 4; +} + +message PingMessage { + Endpoint from = 1; + Endpoint to = 2; + int32 version = 3; + int64 timestamp = 4; +} + +message PongMessage { + Endpoint from = 1; + int32 echo = 2; + int64 timestamp = 3; +} + +message FindNeighbours { + Endpoint from = 1; + bytes targetId = 2; + int64 timestamp = 3; +} + +message Neighbours { + Endpoint from = 1; + repeated Endpoint neighbours = 2; + int64 timestamp = 3; +} + +message EndPoints { + repeated Endpoint nodes = 1; +} + +message DnsRoot { + message TreeRoot { + bytes eRoot = 1; + bytes lRoot = 2; + int32 seq = 3; + } + TreeRoot treeRoot = 1; + bytes signature = 2; +} diff --git a/p2p/src/test/java/org/tron/p2p/P2pServiceTest.java b/p2p/src/test/java/org/tron/p2p/P2pServiceTest.java new file mode 100644 index 00000000000..b7832e7e94e --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/P2pServiceTest.java @@ -0,0 +1,118 @@ +package org.tron.p2p; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.discover.Node; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.stats.P2pStats; +import org.tron.p2p.utils.TestPort; + +/** + * P2pService is the library's public entry point: everything java-tron calls + * goes through it. Exercised against a started service on a free port with + * discovery off, so no traffic leaves the host. + */ +public class P2pServiceTest { + + private P2pConfig saved; + private P2pService service; + private List savedHandlerList; + private Map savedHandlerMap; + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + P2pConfig config = new P2pConfig(); + config.setIp("127.0.0.1"); + // A fixed port would collide with the other p2p tests sharing this task. + config.setPort(TestPort.choose()); + config.setDiscoverEnable(false); + config.setDisconnectionPolicyEnable(false); + + // register() writes into process-wide registries that nothing else resets, + // so snapshot them and put the originals back afterwards. + savedHandlerList = new ArrayList<>(Parameter.handlerList); + savedHandlerMap = new HashMap<>(Parameter.handlerMap); + + service = new P2pService(); + service.start(config); + } + + @After + public void tearDown() { + service.close(); + ChannelManager.isShutdown = false; + Parameter.handlerList = savedHandlerList; + Parameter.handlerMap = savedHandlerMap; + Parameter.p2pConfig = saved; + } + + @Test + public void startPublishesTheConfig() { + Assert.assertEquals("127.0.0.1", Parameter.p2pConfig.getIp()); + Assert.assertEquals(Parameter.version, service.getVersion()); + } + + @Test + public void nodeListsAreQueryableAndNeverNull() { + List table = service.getTableNodes(); + List connectable = service.getConnectableNodes(); + List all = service.getAllNodes(); + + Assert.assertNotNull(table); + Assert.assertNotNull(connectable); + Assert.assertNotNull(all); + // getAllNodes unions the discovery table with the DNS nodes, so it can never + // be smaller than the table alone. + Assert.assertTrue(all.size() >= table.size()); + } + + @Test + public void statsAreExposed() { + P2pStats stats = service.getP2pStats(); + Assert.assertNotNull(stats); + Assert.assertTrue(stats.getTcpInPackets() >= 0); + Assert.assertTrue(stats.getUdpOutSize() >= 0); + } + + @Test + public void registeringTheSameMessageTypeTwiceIsRejected() throws Exception { + P2pEventHandler first = new P2pEventHandler() { + @Override + public void onMessage(Channel channel, byte[] data) { + } + }; + first.messageTypes = new java.util.HashSet<>(java.util.Collections.singletonList((byte) 0x7A)); + service.register(first); + + P2pEventHandler clash = new P2pEventHandler() { + @Override + public void onMessage(Channel channel, byte[] data) { + } + }; + clash.messageTypes = new java.util.HashSet<>(java.util.Collections.singletonList((byte) 0x7A)); + try { + service.register(clash); + Assert.fail("expected a P2pException for the duplicate type"); + } catch (P2pException expected) { + Assert.assertEquals(P2pException.TypeEnum.TYPE_ALREADY_REGISTERED, expected.getType()); + } + } + + @Test + public void closeIsIdempotent() { + service.close(); + // The second call must return through the isShutdown guard rather than + // tearing the managers down twice. + service.close(); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/ChannelCoreTest.java b/p2p/src/test/java/org/tron/p2p/connection/ChannelCoreTest.java new file mode 100644 index 00000000000..0b7fff8285a --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/ChannelCoreTest.java @@ -0,0 +1,173 @@ +package org.tron.p2p.connection; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.handler.codec.CorruptedFrameException; +import io.netty.handler.timeout.ReadTimeoutException; +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.connection.message.base.P2pDisconnectMessage; +import org.tron.p2p.connection.message.keepalive.PingMessage; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.protos.Connect.DisconnectReason; + +/** + * Channel is the per-peer object every other component holds. These cover the + * parts that do not need a real socket: the send guard, latency averaging, the + * pipeline layout, and the exception classification that decides how a failure + * is logged before the peer is dropped. + */ +public class ChannelCoreTest { + + private static final InetSocketAddress ADDRESS = + new InetSocketAddress("127.0.0.1", 18888); + + private P2pConfig saved; + + private static void attach(Channel channel, EmbeddedChannel netty) throws Exception { + Field ctx = Channel.class.getDeclaredField("ctx"); + ctx.setAccessible(true); + ctx.set(channel, netty.pipeline().firstContext()); + Field address = Channel.class.getDeclaredField("inetSocketAddress"); + address.setAccessible(true); + address.set(channel, ADDRESS); + // close() bans by InetAddress, and Guava's cache rejects a null key, so this + // has to be populated the way setChannelHandlerContext would. + Field inetAddress = Channel.class.getDeclaredField("inetAddress"); + inetAddress.setAccessible(true); + inetAddress.set(channel, ADDRESS.getAddress()); + } + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + Parameter.p2pConfig = new P2pConfig(); + ChannelManager.getBannedNodes().invalidateAll(); + } + + @After + public void tearDown() { + // close() bans the peer's address for DEFAULT_BAN_TIME in a process-wide + // cache. Left behind, that ban on 127.0.0.1 would make any later test in + // this fork see a recently-disconnected peer. + ChannelManager.getBannedNodes().invalidateAll(); + Parameter.p2pConfig = saved; + } + + @Test + public void initBuildsTheExpectedPipeline() { + EmbeddedChannel netty = new EmbeddedChannel(); + Channel channel = new Channel(); + channel.init(netty.pipeline(), "abcdef", false); + + Assert.assertNotNull(netty.pipeline().get("readTimeoutHandler")); + Assert.assertNotNull(netty.pipeline().get("protoPrepend")); + Assert.assertNotNull(netty.pipeline().get("protoDecode")); + Assert.assertNotNull(netty.pipeline().get("messageHandler")); + // A non-empty node id means we initiated the connection. + Assert.assertTrue(channel.isActive()); + Assert.assertFalse(channel.isDiscoveryMode()); + netty.finishAndReleaseAll(); + } + + @Test + public void initWithoutANodeIdIsAnInboundChannel() { + EmbeddedChannel netty = new EmbeddedChannel(); + Channel channel = new Channel(); + channel.init(netty.pipeline(), "", true); + + Assert.assertFalse(channel.isActive()); + Assert.assertTrue(channel.isDiscoveryMode()); + netty.finishAndReleaseAll(); + } + + @Test + public void sendWritesTheFramedMessage() throws Exception { + EmbeddedChannel netty = new EmbeddedChannel(new ChannelInboundHandlerAdapter()); + Channel channel = new Channel(); + attach(channel, netty); + + channel.send(new PingMessage()); + netty.flushOutbound(); + + ByteBuf written = netty.readOutbound(); + Assert.assertNotNull("a ping should have been written", written); + Assert.assertEquals(MessageType.KEEP_ALIVE_PING.getType(), written.getByte(0)); + Assert.assertTrue(channel.getLastSendTime() > 0); + netty.finishAndReleaseAll(); + } + + @Test + public void sendIsSuppressedOnceDisconnected() throws Exception { + EmbeddedChannel netty = new EmbeddedChannel(new ChannelInboundHandlerAdapter()); + Channel channel = new Channel(); + attach(channel, netty); + channel.setDisconnect(true); + + channel.send(new P2pDisconnectMessage(DisconnectReason.PEER_QUITING)); + netty.flushOutbound(); + + Assert.assertNull("nothing may be written after disconnect", netty.readOutbound()); + netty.finishAndReleaseAll(); + } + + @Test + public void updateAvgLatencyIsARunningMean() { + Channel channel = new Channel(); + Assert.assertEquals(0, channel.getAvgLatency()); + + channel.updateAvgLatency(10); + Assert.assertEquals(10, channel.getAvgLatency()); + + channel.updateAvgLatency(20); + Assert.assertEquals(15, channel.getAvgLatency()); + + channel.updateAvgLatency(30); + Assert.assertEquals(20, channel.getAvgLatency()); + } + + @Test + public void processExceptionClassifiesAndCloses() throws Exception { + for (Throwable throwable : new Throwable[] { + ReadTimeoutException.INSTANCE, + new IOException("reset by peer"), + new CorruptedFrameException("bad frame"), + new P2pException(P2pException.TypeEnum.BAD_MESSAGE, "nope"), + new RuntimeException("unexpected")}) { + EmbeddedChannel netty = new EmbeddedChannel(new ChannelInboundHandlerAdapter()); + Channel channel = new Channel(); + attach(channel, netty); + + channel.processException(throwable); + + // Whatever the classification, the peer is dropped. + Assert.assertTrue("channel should be marked disconnected for " + throwable, + channel.isDisconnect()); + netty.finishAndReleaseAll(); + } + } + + @Test + public void closeRecordsTheDisconnectTime() throws Exception { + EmbeddedChannel netty = new EmbeddedChannel(new ChannelInboundHandlerAdapter()); + Channel channel = new Channel(); + attach(channel, netty); + + long before = System.currentTimeMillis(); + channel.close(); + + Assert.assertTrue(channel.isDisconnect()); + Assert.assertTrue(channel.getDisconnectTime() >= before); + netty.finishAndReleaseAll(); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/ChannelManagerAdmissionTest.java b/p2p/src/test/java/org/tron/p2p/connection/ChannelManagerAdmissionTest.java new file mode 100644 index 00000000000..bc544e26dd7 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/ChannelManagerAdmissionTest.java @@ -0,0 +1,174 @@ +package org.tron.p2p.connection; + +import java.lang.reflect.Field; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.Map; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.business.handshake.DisconnectCode; +import org.tron.p2p.protos.Connect.DisconnectReason; +import org.tron.p2p.utils.ByteArray; +import org.tron.p2p.utils.NetUtil; + +/** + * processPeer is the admission decision for every inbound connection: ban list, + * global cap, per-IP cap, then duplicate-nodeId resolution. Each branch here is + * what stops a single host from taking every slot. + */ +public class ChannelManagerAdmissionTest { + + private P2pConfig saved; + private Map channels; + + private static Channel channelAt(String ip, int port) throws Exception { + Channel channel = new Channel(); + InetSocketAddress address = new InetSocketAddress(ip, port); + Field socket = Channel.class.getDeclaredField("inetSocketAddress"); + socket.setAccessible(true); + socket.set(channel, address); + Field inet = Channel.class.getDeclaredField("inetAddress"); + inet.setAccessible(true); + inet.set(channel, address.getAddress()); + return channel; + } + + private static void setNodeId(Channel channel, String nodeId) throws Exception { + Field field = Channel.class.getDeclaredField("nodeId"); + field.setAccessible(true); + field.set(channel, nodeId); + } + + private static void setStartTime(Channel channel, long startTime) throws Exception { + Field field = Channel.class.getDeclaredField("startTime"); + field.setAccessible(true); + field.set(channel, startTime); + } + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + P2pConfig config = new P2pConfig(); + config.setMaxConnections(2); + config.setMaxConnectionsWithSameIp(1); + Parameter.p2pConfig = config; + + channels = ChannelManager.getChannels(); + channels.clear(); + ChannelManager.getBannedNodes().invalidateAll(); + } + + @After + public void tearDown() { + channels.clear(); + ChannelManager.getBannedNodes().invalidateAll(); + Parameter.p2pConfig = saved; + } + + @Test + public void aFreshPeerIsAdmitted() throws Exception { + Channel channel = channelAt("127.0.0.1", 10001); + Assert.assertEquals(DisconnectCode.NORMAL, ChannelManager.processPeer(channel)); + Assert.assertSame(channel, channels.get(channel.getInetSocketAddress())); + } + + @Test + public void aRecentlyBannedPeerIsRefused() throws Exception { + Channel channel = channelAt("127.0.0.1", 10001); + ChannelManager.banNode(channel.getInetAddress(), 60_000L); + + Assert.assertEquals(DisconnectCode.TIME_BANNED, ChannelManager.processPeer(channel)); + Assert.assertTrue(channels.isEmpty()); + } + + @Test + public void anExpiredBanNoLongerBlocks() throws Exception { + Channel channel = channelAt("127.0.0.1", 10001); + // banNode stores an absolute expiry; a zero ban is already in the past. + ChannelManager.banNode(channel.getInetAddress(), 0L); + + Assert.assertEquals(DisconnectCode.NORMAL, ChannelManager.processPeer(channel)); + } + + @Test + public void theGlobalCapIsEnforced() throws Exception { + Assert.assertEquals(DisconnectCode.NORMAL, + ChannelManager.processPeer(channelAt("127.0.0.1", 10001))); + Assert.assertEquals(DisconnectCode.NORMAL, + ChannelManager.processPeer(channelAt("127.0.0.2", 10002))); + + // maxConnections is 2, so the third is refused. + Assert.assertEquals(DisconnectCode.TOO_MANY_PEERS, + ChannelManager.processPeer(channelAt("127.0.0.3", 10003))); + } + + @Test + public void thePerIpCapIsEnforced() throws Exception { + Parameter.p2pConfig.setMaxConnections(10); + Assert.assertEquals(DisconnectCode.NORMAL, + ChannelManager.processPeer(channelAt("127.0.0.1", 10001))); + + // maxConnectionsWithSameIp is 1, so a second socket from the same host is + // refused even though the global cap has room. + Assert.assertEquals(DisconnectCode.MAX_CONNECTION_WITH_SAME_IP, + ChannelManager.processPeer(channelAt("127.0.0.1", 10002))); + } + + @Test + public void connectionNumCountsOnlyTheSameAddress() throws Exception { + ChannelManager.processPeer(channelAt("127.0.0.1", 10001)); + Assert.assertEquals(1, + ChannelManager.getConnectionNum(InetAddress.getByName("127.0.0.1"))); + Assert.assertEquals(0, + ChannelManager.getConnectionNum(InetAddress.getByName("127.0.0.2"))); + } + + @Test + public void theOlderConnectionWinsADuplicateNodeId() throws Exception { + Parameter.p2pConfig.setMaxConnections(10); + Parameter.p2pConfig.setMaxConnectionsWithSameIp(10); + String nodeId = ByteArray.toHexString(NetUtil.getNodeId()); + + Channel first = channelAt("127.0.0.1", 10001); + setNodeId(first, nodeId); + setStartTime(first, 1000L); + Assert.assertEquals(DisconnectCode.NORMAL, ChannelManager.processPeer(first)); + + // The newcomer started later, so it is the duplicate and is refused. + Channel later = channelAt("127.0.0.2", 10002); + setNodeId(later, nodeId); + setStartTime(later, 2000L); + Assert.assertEquals(DisconnectCode.DUPLICATE_PEER, ChannelManager.processPeer(later)); + } + + @Test + public void everyDisconnectCodeMapsToAReason() { + Assert.assertEquals(DisconnectReason.DIFFERENT_VERSION, + ChannelManager.getDisconnectReason(DisconnectCode.DIFFERENT_VERSION)); + Assert.assertEquals(DisconnectReason.RECENT_DISCONNECT, + ChannelManager.getDisconnectReason(DisconnectCode.TIME_BANNED)); + Assert.assertEquals(DisconnectReason.DUPLICATE_PEER, + ChannelManager.getDisconnectReason(DisconnectCode.DUPLICATE_PEER)); + Assert.assertEquals(DisconnectReason.TOO_MANY_PEERS, + ChannelManager.getDisconnectReason(DisconnectCode.TOO_MANY_PEERS)); + Assert.assertEquals(DisconnectReason.TOO_MANY_PEERS_WITH_SAME_IP, + ChannelManager.getDisconnectReason(DisconnectCode.MAX_CONNECTION_WITH_SAME_IP)); + Assert.assertEquals(DisconnectReason.UNKNOWN, + ChannelManager.getDisconnectReason(DisconnectCode.NORMAL)); + } + + @Test + public void banNodeKeepsTheLongerOfTwoBans() throws Exception { + InetAddress address = InetAddress.getByName("127.0.0.9"); + ChannelManager.banNode(address, 60_000L); + Long first = ChannelManager.getBannedNodes().getIfPresent(address); + + // A shorter ban must not shorten an existing longer one. + ChannelManager.banNode(address, 1L); + Assert.assertEquals(first, ChannelManager.getBannedNodes().getIfPresent(address)); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/ChannelManagerTest.java b/p2p/src/test/java/org/tron/p2p/connection/ChannelManagerTest.java new file mode 100644 index 00000000000..eb772a23d91 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/ChannelManagerTest.java @@ -0,0 +1,185 @@ +package org.tron.p2p.connection; + +import com.google.protobuf.ByteString; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.embedded.EmbeddedChannel; +import java.lang.reflect.Field; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.ArrayUtils; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.business.handshake.DisconnectCode; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.protos.Connect; +import org.tron.p2p.protos.Discover; + +@Slf4j(topic = "net") +public class ChannelManagerTest { + + @Test + public synchronized void testGetConnectionNum() throws Exception { + Channel c1 = new Channel(); + InetSocketAddress a1 = new InetSocketAddress("100.1.1.1", 100); + Field field = c1.getClass().getDeclaredField("inetAddress"); + field.setAccessible(true); + field.set(c1, a1.getAddress()); + + Channel c2 = new Channel(); + InetSocketAddress a2 = new InetSocketAddress("100.1.1.2", 100); + field = c2.getClass().getDeclaredField("inetAddress"); + field.setAccessible(true); + field.set(c2, a2.getAddress()); + + Channel c3 = new Channel(); + InetSocketAddress a3 = new InetSocketAddress("100.1.1.2", 99); + field = c3.getClass().getDeclaredField("inetAddress"); + field.setAccessible(true); + field.set(c3, a3.getAddress()); + + int cnt = ChannelManager.getConnectionNum(a1.getAddress()); + Assert.assertTrue(cnt == 0); + + ChannelManager.getChannels().put(a1, c1); + cnt = ChannelManager.getConnectionNum(a1.getAddress()); + Assert.assertTrue(cnt == 1); + + ChannelManager.getChannels().put(a2, c2); + cnt = ChannelManager.getConnectionNum(a2.getAddress()); + Assert.assertTrue(cnt == 1); + + ChannelManager.getChannels().put(a3, c3); + cnt = ChannelManager.getConnectionNum(a3.getAddress()); + Assert.assertTrue(cnt == 2); + } + + @Test + public synchronized void testNotifyDisconnect() throws Exception { + Channel c1 = new Channel(); + InetSocketAddress a1 = new InetSocketAddress("100.1.1.1", 100); + + Field field = c1.getClass().getDeclaredField("inetSocketAddress"); + field.setAccessible(true); + field.set(c1, a1); + + InetAddress inetAddress = a1.getAddress(); + field = c1.getClass().getDeclaredField("inetAddress"); + field.setAccessible(true); + field.set(c1, inetAddress); + + ChannelManager.getChannels().put(a1, c1); + + Long time = ChannelManager.getBannedNodes().getIfPresent(a1.getAddress()); + Assert.assertTrue(ChannelManager.getChannels().size() == 1); + Assert.assertTrue(time == null); + + ChannelManager.notifyDisconnect(c1); + time = ChannelManager.getBannedNodes().getIfPresent(a1.getAddress()); + Assert.assertTrue(time != null); + Assert.assertTrue(ChannelManager.getChannels().size() == 0); + } + + @Test + public synchronized void testProcessPeer() throws Exception { + clearChannels(); + Parameter.p2pConfig = new P2pConfig(); + + Channel c1 = new Channel(); + InetSocketAddress a1 = new InetSocketAddress("100.1.1.2", 100); + + Field field = c1.getClass().getDeclaredField("inetSocketAddress"); + field.setAccessible(true); + field.set(c1, a1); + field = c1.getClass().getDeclaredField("inetAddress"); + field.setAccessible(true); + field.set(c1, a1.getAddress()); + + DisconnectCode code = ChannelManager.processPeer(c1); + Assert.assertTrue(code.equals(DisconnectCode.NORMAL)); + + Thread.sleep(5); + + Parameter.p2pConfig.setMaxConnections(1); + + Channel c2 = new Channel(); + InetSocketAddress a2 = new InetSocketAddress("100.1.1.2", 99); + + field = c2.getClass().getDeclaredField("inetSocketAddress"); + field.setAccessible(true); + field.set(c2, a2); + field = c2.getClass().getDeclaredField("inetAddress"); + field.setAccessible(true); + field.set(c2, a2.getAddress()); + + code = ChannelManager.processPeer(c2); + Assert.assertTrue(code.equals(DisconnectCode.TOO_MANY_PEERS)); + + Parameter.p2pConfig.setMaxConnections(2); + Parameter.p2pConfig.setMaxConnectionsWithSameIp(1); + code = ChannelManager.processPeer(c2); + Assert.assertTrue(code.equals(DisconnectCode.MAX_CONNECTION_WITH_SAME_IP)); + + Parameter.p2pConfig.setMaxConnectionsWithSameIp(2); + c1.setNodeId("cc"); + c2.setNodeId("cc"); + code = ChannelManager.processPeer(c2); + Assert.assertTrue(code.equals(DisconnectCode.DUPLICATE_PEER)); + } + + private void clearChannels() { + ChannelManager.getChannels().clear(); + ChannelManager.getBannedNodes().invalidateAll(); + } + + @Test + public synchronized void testDiscoveryModeRejectsHelloMessage() throws Exception { + clearChannels(); + Parameter.p2pConfig = new P2pConfig(); + + Channel channel = new Channel(); + channel.setDiscoveryMode(true); + + InetSocketAddress addr = new InetSocketAddress("100.1.1.5", 18888); + Field f = channel.getClass().getDeclaredField("inetSocketAddress"); + f.setAccessible(true); + f.set(channel, addr); + f = channel.getClass().getDeclaredField("inetAddress"); + f.setAccessible(true); + f.set(channel, addr.getAddress()); + + EmbeddedChannel ec = new EmbeddedChannel(new ChannelInboundHandlerAdapter()); + ChannelHandlerContext ctx = ec.pipeline().firstContext(); + f = channel.getClass().getDeclaredField("ctx"); + f.setAccessible(true); + f.set(channel, ctx); + + byte[] helloBytes = buildHelloMessageBytes(); + + ChannelManager.processMessage(channel, helloBytes); + + Assert.assertTrue(channel.isDisconnect()); + Assert.assertNull(channel.getHelloMessage()); + Assert.assertFalse(channel.isFinishHandshake()); + Assert.assertFalse(ChannelManager.getChannels().containsKey(addr)); + } + + private byte[] buildHelloMessageBytes() { + Discover.Endpoint endpoint = Discover.Endpoint.newBuilder() + .setNodeId(ByteString.copyFrom(new byte[64])) + .setAddress(ByteString.copyFromUtf8("127.0.0.1")) + .setPort(18888) + .build(); + Connect.HelloMessage hello = Connect.HelloMessage.newBuilder() + .setFrom(endpoint) + .setNetworkId(1) + .setCode(DisconnectCode.NORMAL.getValue()) + .setVersion(1) + .setTimestamp(System.currentTimeMillis()) + .build(); + return ArrayUtils.add(hello.toByteArray(), 0, MessageType.HANDSHAKE_HELLO.getType()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/ChannelValueTest.java b/p2p/src/test/java/org/tron/p2p/connection/ChannelValueTest.java new file mode 100644 index 00000000000..0fb6da475b0 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/ChannelValueTest.java @@ -0,0 +1,69 @@ +package org.tron.p2p.connection; + +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import org.junit.Assert; +import org.junit.Test; + +/** + * Covers Channel's value semantics and latency accounting — the parts that do not + * need a live connection. Identity matters because channels are held in sets and + * maps keyed by peer, so equals/hashCode drive connection de-duplication. + */ +public class ChannelValueTest { + + private static Channel channelAt(String host, int port) throws Exception { + Channel channel = new Channel(); + Field field = Channel.class.getDeclaredField("inetSocketAddress"); + field.setAccessible(true); + field.set(channel, new InetSocketAddress(host, port)); + return channel; + } + + @Test + public void updateAvgLatencyKeepsARunningMean() { + Channel channel = new Channel(); + // running mean: 10 -> 10, then (10+20)/2 = 15, then (15*2+30)/3 = 20 + channel.updateAvgLatency(10); + Assert.assertEquals(10, channel.getAvgLatency()); + channel.updateAvgLatency(20); + Assert.assertEquals(15, channel.getAvgLatency()); + channel.updateAvgLatency(30); + Assert.assertEquals(20, channel.getAvgLatency()); + } + + @Test + public void updateAvgLatencyFromZero() { + Channel channel = new Channel(); + // the first sample defines the mean, with no division-by-zero on count + channel.updateAvgLatency(0); + Assert.assertEquals(0, channel.getAvgLatency()); + channel.updateAvgLatency(100); + Assert.assertEquals(50, channel.getAvgLatency()); + } + + @Test + public void equalityIsByRemoteAddress() throws Exception { + Channel a = channelAt("127.0.0.1", 10000); + Channel sameAddress = channelAt("127.0.0.1", 10000); + Channel otherPort = channelAt("127.0.0.1", 10001); + Channel otherHost = channelAt("127.0.0.2", 10000); + + Assert.assertEquals(a, a); + Assert.assertEquals(a, sameAddress); + Assert.assertNotEquals(a, otherPort); + Assert.assertNotEquals(a, otherHost); + + Assert.assertNotEquals(a, null); + Assert.assertNotEquals(a, "not a channel"); + } + + @Test + public void hashCodeAgreesWithEquals() throws Exception { + Channel a = channelAt("127.0.0.1", 10000); + Channel sameAddress = channelAt("127.0.0.1", 10000); + // equal channels must hash equally, or set/map de-duplication breaks + Assert.assertEquals(a.hashCode(), sameAddress.hashCode()); + Assert.assertEquals(new InetSocketAddress("127.0.0.1", 10000).hashCode(), a.hashCode()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/ConnPoolServiceTest.java b/p2p/src/test/java/org/tron/p2p/connection/ConnPoolServiceTest.java new file mode 100644 index 00000000000..f58b69edc4f --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/ConnPoolServiceTest.java @@ -0,0 +1,186 @@ +package org.tron.p2p.connection; + +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.business.pool.ConnPoolService; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.NodeManager; +import org.tron.p2p.utils.TestPort; + +public class ConnPoolServiceTest { + + private static String localIp = "127.0.0.1"; + // A fixed port collides with SocketTest and with other forks of this task. + // PeerServer.start only logs on bind failure, so a collision used to let this + // class pass while exercising nothing. + private static int port = TestPort.choose(); + + @BeforeClass + public static void init() { + Parameter.p2pConfig = new P2pConfig(); + Parameter.p2pConfig.setDiscoverEnable(false); + Parameter.p2pConfig.setPort(port); + + NodeManager.init(); + ChannelManager.init(); + } + + private void clearChannels() { + ChannelManager.getChannels().clear(); + ChannelManager.getBannedNodes().invalidateAll(); + } + + @Test + public void getNodes_chooseHomeNode() { + InetSocketAddress localAddress = new InetSocketAddress(Parameter.p2pConfig.getIp(), + Parameter.p2pConfig.getPort()); + Set inetInUse = new HashSet<>(); + inetInUse.add(localAddress); + + List connectableNodes = new ArrayList<>(); + connectableNodes.add(NodeManager.getHomeNode()); + + ConnPoolService connPoolService = new ConnPoolService(); + List nodes = connPoolService.getNodes(new HashSet<>(), inetInUse, connectableNodes, + 1); + Assert.assertEquals(0, nodes.size()); + + nodes = connPoolService.getNodes(new HashSet<>(), new HashSet<>(), connectableNodes, + 1); + Assert.assertEquals(1, nodes.size()); + } + + @Test + public void getNodes_orderByUpdateTimeDesc() throws Exception { + clearChannels(); + Node node1 = new Node(new InetSocketAddress(localIp, 90)); + Field field = node1.getClass().getDeclaredField("updateTime"); + field.setAccessible(true); + field.set(node1, System.currentTimeMillis()); + + Node node2 = new Node(new InetSocketAddress(localIp, 100)); + field = node2.getClass().getDeclaredField("updateTime"); + field.setAccessible(true); + field.set(node2, System.currentTimeMillis() + 10); + + Assert.assertTrue(node1.getUpdateTime() < node2.getUpdateTime()); + + List connectableNodes = new ArrayList<>(); + connectableNodes.add(node1); + connectableNodes.add(node2); + + ConnPoolService connPoolService = new ConnPoolService(); + List nodes = connPoolService.getNodes(new HashSet<>(), new HashSet<>(), connectableNodes, + 2); + Assert.assertEquals(2, nodes.size()); + // getNodes() sorts candidates by updateTime descending, but then calls + // Collections.shuffle() before truncating to `limit`, so the order of the + // returned list is deliberately randomised. Assert membership, not order — + // asserting order here is a coin flip with two nodes. The effect of the + // descending sort is covered by getNodes_prefersNewestAboveCandidateSize(). + Set returnedTimes = new HashSet<>(); + for (Node node : nodes) { + returnedTimes.add(node.getUpdateTime()); + } + Assert.assertTrue(returnedTimes.contains(node1.getUpdateTime())); + Assert.assertTrue(returnedTimes.contains(node2.getUpdateTime())); + + int limit = 1; + List nodes2 = connPoolService.getNodes(new HashSet<>(), new HashSet<>(), connectableNodes, + limit); + Assert.assertEquals(limit, nodes2.size()); + } + + /** + * getNodes() keeps only the newest max(limit * 10, minCandidateSize) candidates + * before shuffling, with minCandidateSize = 50. The descending sort is therefore + * only observable once the candidate list exceeds that bound, which is what this + * test exercises: with 60 candidates and limit 1, the 10 oldest must never be + * returned no matter how the shuffle falls. + */ + @Test + public void getNodes_prefersNewestAboveCandidateSize() throws Exception { + clearChannels(); + final int total = 60; + final int candidateSize = 50; + long base = System.currentTimeMillis(); + + List connectableNodes = new ArrayList<>(); + for (int i = 0; i < total; i++) { + Node node = new Node(new InetSocketAddress(localIp, 20000 + i)); + Field field = node.getClass().getDeclaredField("updateTime"); + field.setAccessible(true); + // Node i gets updateTime base + i, so nodes 0..9 are the 10 oldest. + field.set(node, base + i); + connectableNodes.add(node); + } + + long oldestRetainedTime = base + (total - candidateSize); + ConnPoolService connPoolService = new ConnPoolService(); + // Repeat: a single draw could miss a mis-sorted entry by luck. + for (int round = 0; round < 20; round++) { + List nodes = connPoolService.getNodes(new HashSet<>(), new HashSet<>(), + connectableNodes, 1); + Assert.assertEquals(1, nodes.size()); + Assert.assertTrue("returned a node older than the newest " + candidateSize + " candidates", + nodes.get(0).getUpdateTime() >= oldestRetainedTime); + } + } + + @Test + public void getNodes_banNode() throws InterruptedException { + clearChannels(); + InetSocketAddress inetSocketAddress = new InetSocketAddress(localIp, 90); + long banTime = 500L; + ChannelManager.banNode(inetSocketAddress.getAddress(), banTime); + Node node = new Node(inetSocketAddress); + List connectableNodes = new ArrayList<>(); + connectableNodes.add(node); + + ConnPoolService connPoolService = new ConnPoolService(); + List nodes = connPoolService.getNodes(new HashSet<>(), new HashSet<>(), connectableNodes, + 1); + Assert.assertEquals(0, nodes.size()); + Thread.sleep(2 * banTime); + + nodes = connPoolService.getNodes(new HashSet<>(), new HashSet<>(), connectableNodes, 1); + Assert.assertEquals(1, nodes.size()); + } + + @Test + public void getNodes_nodeInUse() { + clearChannels(); + InetSocketAddress inetSocketAddress = new InetSocketAddress(localIp, 90); + Node node = new Node(inetSocketAddress); + List connectableNodes = new ArrayList<>(); + connectableNodes.add(node); + + Set nodesInUse = new HashSet<>(); + nodesInUse.add(node.getHexId()); + ConnPoolService connPoolService = new ConnPoolService(); + List nodes = connPoolService.getNodes(nodesInUse, new HashSet<>(), connectableNodes, 1); + Assert.assertEquals(0, nodes.size()); + } + + @AfterClass + public static void destroy() { + NodeManager.close(); + ChannelManager.close(); + // ChannelManager.close() latches isShutdown, and init() does not clear it. In + // libp2p's own module that was harmless (one class per run, and its CI never ran + // tests); here framework reuses a JVM across up to 100 classes, so leaving it set + // makes every later PeerClient.connect() return null and ConnPoolService skip + // reconnection. Reset it so the next class starts from a clean state. + ChannelManager.isShutdown = false; + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/DisconnectReasonMappingTest.java b/p2p/src/test/java/org/tron/p2p/connection/DisconnectReasonMappingTest.java new file mode 100644 index 00000000000..711e1fd4ce9 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/DisconnectReasonMappingTest.java @@ -0,0 +1,51 @@ +package org.tron.p2p.connection; + +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.connection.business.handshake.DisconnectCode; +import org.tron.p2p.protos.Connect.DisconnectReason; + +/** + * Covers the DisconnectCode -> DisconnectReason mapping. The code is what a peer sends + * on the wire; the reason is what we record and report. Two of the pairs are deliberately + * not same-named, so a careless edit here silently mislabels why peers were dropped. + */ +public class DisconnectReasonMappingTest { + + @Test + public void mapsEachHandshakeCodeToItsReason() { + Assert.assertEquals(DisconnectReason.DIFFERENT_VERSION, + ChannelManager.getDisconnectReason(DisconnectCode.DIFFERENT_VERSION)); + Assert.assertEquals(DisconnectReason.DUPLICATE_PEER, + ChannelManager.getDisconnectReason(DisconnectCode.DUPLICATE_PEER)); + Assert.assertEquals(DisconnectReason.TOO_MANY_PEERS, + ChannelManager.getDisconnectReason(DisconnectCode.TOO_MANY_PEERS)); + } + + @Test + public void mapsTheTwoCodesThatChangeName() { + // TIME_BANNED is reported as RECENT_DISCONNECT + Assert.assertEquals(DisconnectReason.RECENT_DISCONNECT, + ChannelManager.getDisconnectReason(DisconnectCode.TIME_BANNED)); + // MAX_CONNECTION_WITH_SAME_IP is reported as TOO_MANY_PEERS_WITH_SAME_IP + Assert.assertEquals(DisconnectReason.TOO_MANY_PEERS_WITH_SAME_IP, + ChannelManager.getDisconnectReason(DisconnectCode.MAX_CONNECTION_WITH_SAME_IP)); + } + + @Test + public void mapsEveryOtherCodeToUnknown() { + // NORMAL has no disconnect reason of its own, and any code added later must fall + // through to UNKNOWN rather than to whatever case precedes it + Assert.assertEquals(DisconnectReason.UNKNOWN, + ChannelManager.getDisconnectReason(DisconnectCode.NORMAL)); + } + + @Test + public void mappingIsTotalOverTheEnum() { + // no code may produce a null reason, since the result is logged unguarded + for (DisconnectCode code : DisconnectCode.values()) { + Assert.assertNotNull("no reason mapped for " + code, + ChannelManager.getDisconnectReason(code)); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/MessageTest.java b/p2p/src/test/java/org/tron/p2p/connection/MessageTest.java new file mode 100644 index 00000000000..84ae0260535 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/MessageTest.java @@ -0,0 +1,87 @@ +package org.tron.p2p.connection; + +import static org.tron.p2p.base.Parameter.NETWORK_TIME_DIFF; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.business.handshake.DisconnectCode; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.connection.message.handshake.HelloMessage; +import org.tron.p2p.connection.message.keepalive.PingMessage; +import org.tron.p2p.connection.message.keepalive.PongMessage; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.exception.P2pException.TypeEnum; +import org.tron.p2p.protos.Connect; +import org.tron.p2p.protos.Connect.KeepAliveMessage; + +public class MessageTest { + + @Before + public void init() { + Parameter.p2pConfig = new P2pConfig(); + } + + @Test + public void testPing() { + PingMessage pingMessage = new PingMessage(); + byte[] messageData = pingMessage.getSendData(); + try { + Message message = Message.parse(messageData); + Assert.assertEquals(MessageType.KEEP_ALIVE_PING, message.getType()); + } catch (P2pException e) { + Assert.fail(); + } + } + + @Test + public void testPong() { + PongMessage pongMessage = new PongMessage(); + byte[] messageData = pongMessage.getSendData(); + try { + Message message = Message.parse(messageData); + Assert.assertEquals(MessageType.KEEP_ALIVE_PONG, message.getType()); + } catch (P2pException e) { + Assert.fail(); + } + } + + @Test + public void testHandShakeHello() { + HelloMessage helloMessage = new HelloMessage(DisconnectCode.NORMAL, 0); + byte[] messageData = helloMessage.getSendData(); + try { + Message message = Message.parse(messageData); + Assert.assertEquals(MessageType.HANDSHAKE_HELLO, message.getType()); + } catch (P2pException e) { + Assert.fail(); + } + } + + @Test + public void testUnKnownType() { + PingMessage pingMessage = new PingMessage(); + byte[] messageData = pingMessage.getSendData(); + messageData[0] = (byte) 0x00; + try { + Message.parse(messageData); + } catch (P2pException e) { + Assert.assertEquals(TypeEnum.NO_SUCH_MESSAGE, e.getType()); + } + } + + @Test + public void testInvalidTime() { + KeepAliveMessage keepAliveMessage = Connect.KeepAliveMessage.newBuilder() + .setTimestamp(System.currentTimeMillis() + NETWORK_TIME_DIFF * 2).build(); + try { + PingMessage message = new PingMessage(keepAliveMessage.toByteArray()); + Assert.assertFalse(message.valid()); + } catch (Exception e) { + Assert.fail(); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/SocketTest.java b/p2p/src/test/java/org/tron/p2p/connection/SocketTest.java new file mode 100644 index 00000000000..eee8d03b50a --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/SocketTest.java @@ -0,0 +1,82 @@ +package org.tron.p2p.connection; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFutureListener; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.discover.NodeManager; +import org.tron.p2p.utils.TestPort; + +public class SocketTest { + + private static String localIp = "127.0.0.1"; + // See ConnPoolServiceTest: a fixed port silently no-ops on collision. + private static int port = TestPort.choose(); + + @Before + public void init() { + Parameter.p2pConfig = new P2pConfig(); + Parameter.p2pConfig.setIp(localIp); + Parameter.p2pConfig.setPort(port); + Parameter.p2pConfig.setDiscoverEnable(false); + + NodeManager.init(); + ChannelManager.init(); + } + + private boolean sendMessage(io.netty.channel.Channel nettyChannel, Message message) { + AtomicBoolean sendSuccess = new AtomicBoolean(false); + nettyChannel.writeAndFlush(Unpooled.wrappedBuffer(message.getSendData())) + .addListener((ChannelFutureListener) future -> { + if (future.isSuccess()) { + sendSuccess.set(true); + } else { + sendSuccess.set(false); + } + }); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + return sendSuccess.get(); + } + + //if we start handshake, we cannot connect with localhost, this test case will be invalid + @Test + public void testPeerServerAndPeerClient() throws InterruptedException { + // //wait some time until peer server thread starts at this port successfully + // Thread.sleep(500); + // Node serverNode = new Node(new InetSocketAddress(localIp, port)); + // + // //peer client try to connect peer server using random port + // io.netty.channel.Channel nettyChannel = ChannelManager.getPeerClient() + // .connectAsync(serverNode, false, false).channel(); + // + // while (true) { + // if (!nettyChannel.isActive()) { + // Thread.sleep(100); + // } else { + // System.out.println("send message test"); + // PingMessage pingMessage = new PingMessage(); + // boolean sendSuccess = sendMessage(nettyChannel, pingMessage); + // Assert.assertTrue(sendSuccess); + // break; + // } + // } + } + + @After + public void destroy() { + NodeManager.close(); + ChannelManager.close(); + // see ConnPoolServiceTest.destroy(): close() latches isShutdown and init() never + // clears it, which would break every later test sharing this JVM fork + ChannelManager.isShutdown = false; + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/business/detect/NodeDetectServiceTest.java b/p2p/src/test/java/org/tron/p2p/connection/business/detect/NodeDetectServiceTest.java new file mode 100644 index 00000000000..4a0b18b9dcc --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/business/detect/NodeDetectServiceTest.java @@ -0,0 +1,129 @@ +package org.tron.p2p.connection.business.detect; + +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.util.List; +import java.util.Map; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.discover.Node; +import org.tron.p2p.utils.NetUtil; + +/** + * Node detection probes candidate peers with STATUS and keeps a per-address + * NodeStat. The bad-node cache and the trim pass are what stop an unreachable + * address from being retried forever. + */ +public class NodeDetectServiceTest { + + private P2pConfig saved; + private NodeDetectService service; + + @SuppressWarnings("unchecked") + private Map nodeStatMap() throws Exception { + Field field = NodeDetectService.class.getDeclaredField("nodeStatMap"); + field.setAccessible(true); + return (Map) field.get(service); + } + + private static Node nodeAt(String ip, int port) { + return new Node(NetUtil.getNodeId(), ip, null, port, port); + } + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + P2pConfig config = new P2pConfig(); + config.setPort(18888); + config.setIp("127.0.0.1"); + config.setMaxConnections(30); + Parameter.p2pConfig = config; + ChannelManager.getChannels().clear(); + NodeDetectService.getBadNodesCache().invalidateAll(); + service = new NodeDetectService(); + } + + @After + public void tearDown() { + NodeDetectService.getBadNodesCache().invalidateAll(); + ChannelManager.getChannels().clear(); + Parameter.p2pConfig = saved; + } + + @Test + public void nodeStatStartsUnfinishedOnlyAfterADetectIsRecorded() { + NodeStat stat = new NodeStat(nodeAt("127.0.0.1", 10001)); + // Both timestamps are zero to begin with, which counts as finished. + Assert.assertTrue(stat.finishDetect()); + + stat.setLastDetectTime(1000L); + Assert.assertFalse(stat.finishDetect()); + + stat.setLastSuccessDetectTime(1000L); + Assert.assertTrue(stat.finishDetect()); + } + + @Test + public void trimDropsTimedOutProbesAndBansTheAddress() throws Exception { + Node node = nodeAt("127.0.0.1", 10001); + NodeStat stat = new NodeStat(node); + // A detect started long ago and never answered. + stat.setLastDetectTime(System.currentTimeMillis() - 60_000); + nodeStatMap().put(node.getPreferInetSocketAddress(), stat); + + service.trimNodeMap(); + + Assert.assertTrue(nodeStatMap().isEmpty()); + Assert.assertNotNull("the address should be remembered as bad", + NodeDetectService.getBadNodesCache() + .getIfPresent(node.getPreferInetSocketAddress().getAddress())); + } + + @Test + public void trimKeepsAProbeThatIsStillInFlight() throws Exception { + Node node = nodeAt("127.0.0.1", 10001); + NodeStat stat = new NodeStat(node); + stat.setLastDetectTime(System.currentTimeMillis()); + nodeStatMap().put(node.getPreferInetSocketAddress(), stat); + + service.trimNodeMap(); + + Assert.assertEquals(1, nodeStatMap().size()); + } + + @Test + public void trimKeepsACompletedProbe() throws Exception { + Node node = nodeAt("127.0.0.1", 10001); + NodeStat stat = new NodeStat(node); + long when = System.currentTimeMillis() - 60_000; + stat.setLastDetectTime(when); + stat.setLastSuccessDetectTime(when); + nodeStatMap().put(node.getPreferInetSocketAddress(), stat); + + service.trimNodeMap(); + + Assert.assertEquals(1, nodeStatMap().size()); + } + + @Test + public void connectableNodesAreEmptyUntilSomethingAnswers() throws Exception { + Node node = nodeAt("127.0.0.1", 10001); + nodeStatMap().put(node.getPreferInetSocketAddress(), new NodeStat(node)); + + // A NodeStat without a StatusMessage has not answered yet. + List connectable = service.getConnectableNodes(); + Assert.assertNotNull(connectable); + Assert.assertTrue(connectable.isEmpty()); + } + + @Test + public void closeIsSafeToCallTwice() { + service.close(); + service.close(); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/business/handshake/HandshakeServiceTest.java b/p2p/src/test/java/org/tron/p2p/connection/business/handshake/HandshakeServiceTest.java new file mode 100644 index 00000000000..5e1ab1324f6 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/business/handshake/HandshakeServiceTest.java @@ -0,0 +1,226 @@ +package org.tron.p2p.connection.business.handshake; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockedStatic; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.P2pEventHandler; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.connection.message.base.P2pDisconnectMessage; +import org.tron.p2p.connection.message.handshake.HelloMessage; +import org.tron.p2p.discover.Node; +import org.tron.p2p.protos.Connect.DisconnectReason; + +/** + * Covers HandshakeService.processMessage, which decides whether an inbound peer is + * accepted. Every rejection path ends in channel.close(), and getting one wrong either + * admits peers that should be refused or drops peers that are fine, so each branch is + * pinned separately. + * + *

    ChannelManager is stubbed statically because processPeer/updateNodeId consult + * process-wide connection state; the logic under test is HandshakeService's own. + */ +public class HandshakeServiceTest { + + private static final int NETWORK_ID = 11111; + + private MockedStatic channelManager; + private HandshakeService service; + private Channel channel; + private HelloMessage msg; + private List priorHandlers; + + @Before + public void setUp() { + Parameter.p2pConfig = new P2pConfig(); + Parameter.p2pConfig.setNetworkId(NETWORK_ID); + + // handlerList is the process-wide registry P2pService.register() appends to, and + // framework's test task shares a JVM across up to 100 classes. Clearing it outright + // would strip a co-resident test's handlers while leaving handlerMap populated, so a + // later re-register() would throw TYPE_ALREADY_REGISTERED. Save and restore instead. + priorHandlers = new ArrayList<>(Parameter.handlerList); + Parameter.handlerList.clear(); + + channelManager = mockStatic(ChannelManager.class); + channelManager.when(() -> ChannelManager.getDisconnectReason(any(DisconnectCode.class))) + .thenReturn(DisconnectReason.PEER_QUITING); + + service = new HandshakeService(); + + channel = mock(Channel.class); + when(channel.getInetSocketAddress()).thenReturn(new InetSocketAddress("127.0.0.1", 18888)); + when(channel.getStartTime()).thenReturn(System.currentTimeMillis()); + + Node from = new Node(new InetSocketAddress("127.0.0.1", 18888)); + msg = mock(HelloMessage.class); + when(msg.getFrom()).thenReturn(from); + when(msg.getTimestamp()).thenReturn(System.currentTimeMillis()); + when(msg.getCode()).thenReturn(DisconnectCode.NORMAL.getValue()); + when(msg.getNetworkId()).thenReturn(NETWORK_ID); + when(msg.getVersion()).thenReturn(NETWORK_ID); + } + + @After + public void tearDown() { + channelManager.close(); + Parameter.handlerList.clear(); + Parameter.handlerList.addAll(priorHandlers); + } + + private void acceptPeer() { + channelManager.when(() -> ChannelManager.processPeer(any(Channel.class))) + .thenReturn(DisconnectCode.NORMAL); + } + + @Test + public void rejectsASecondHandshakeOnTheSameChannel() { + when(channel.isFinishHandshake()).thenReturn(true); + + service.processMessage(channel, msg); + + verify(channel).send(any(P2pDisconnectMessage.class)); + verify(channel).close(); + // the peer was already accepted; nothing further may be re-evaluated + verify(channel, never()).setFinishHandshake(true); + } + + @Test + public void closesWhenChannelManagerRejectsThePeer() { + channelManager.when(() -> ChannelManager.processPeer(any(Channel.class))) + .thenReturn(DisconnectCode.TOO_MANY_PEERS); + when(channel.isActive()).thenReturn(false); + + service.processMessage(channel, msg); + + // an inbound (non-active) channel is told why before being dropped + verify(channel).send(any(HelloMessage.class)); + verify(channel).close(); + verify(channel, never()).setFinishHandshake(true); + } + + @Test + public void rejectedActiveChannelIsNotSentAHelloBack() { + channelManager.when(() -> ChannelManager.processPeer(any(Channel.class))) + .thenReturn(DisconnectCode.TOO_MANY_PEERS); + when(channel.isActive()).thenReturn(true); + + service.processMessage(channel, msg); + + // we initiated this connection, so there is nothing to reply to + verify(channel, never()).send(any(HelloMessage.class)); + verify(channel).close(); + } + + @Test + public void stopsWhenUpdateNodeIdDisconnectedTheChannel() { + acceptPeer(); + when(channel.isDisconnect()).thenReturn(true); + + service.processMessage(channel, msg); + + // updateNodeId dropped it as a duplicate; no handshake completion, no close here + verify(channel, never()).setFinishHandshake(true); + verify(channel, never()).close(); + } + + @Test + public void completesHandshakeForAnInboundPeer() { + acceptPeer(); + when(channel.isActive()).thenReturn(false); + + service.processMessage(channel, msg); + + verify(channel).send(any(HelloMessage.class)); + verify(channel).setFinishHandshake(true); + verify(channel).updateAvgLatency(org.mockito.ArgumentMatchers.anyLong()); + verify(channel, never()).close(); + } + + @Test + public void completesHandshakeForAnOutboundPeer() { + acceptPeer(); + when(channel.isActive()).thenReturn(true); + + service.processMessage(channel, msg); + + // we already sent our hello when we dialled, so none is sent here + verify(channel, never()).send(any(HelloMessage.class)); + verify(channel).setFinishHandshake(true); + verify(channel, never()).close(); + } + + @Test + public void rejectsInboundPeerOnDifferentNetworkId() { + acceptPeer(); + when(channel.isActive()).thenReturn(false); + when(msg.getNetworkId()).thenReturn(NETWORK_ID + 1); + + service.processMessage(channel, msg); + + // the peer is told the version differs before the channel is dropped + verify(channel).send(any(HelloMessage.class)); + verify(channel).close(); + verify(channel, never()).setFinishHandshake(true); + } + + @Test + public void rejectsOutboundPeerReportingANonNormalCode() { + acceptPeer(); + when(channel.isActive()).thenReturn(true); + when(msg.getCode()).thenReturn(DisconnectCode.TOO_MANY_PEERS.getValue()); + + service.processMessage(channel, msg); + + verify(channel).close(); + verify(channel, never()).setFinishHandshake(true); + } + + @Test + public void rejectsOutboundPeerWhenBothNetworkIdAndVersionDiffer() { + acceptPeer(); + when(channel.isActive()).thenReturn(true); + when(msg.getNetworkId()).thenReturn(NETWORK_ID + 1); + when(msg.getVersion()).thenReturn(NETWORK_ID + 1); + + service.processMessage(channel, msg); + + verify(channel).close(); + verify(channel, never()).setFinishHandshake(true); + } + + @Test + public void acceptsOutboundPeerWhenVersionMatchesEvenIfNetworkIdDoesNot() { + // v0.1 peers carry only a version; the check accepts a match on either field + acceptPeer(); + when(channel.isActive()).thenReturn(true); + when(msg.getNetworkId()).thenReturn(NETWORK_ID + 1); + when(msg.getVersion()).thenReturn(NETWORK_ID); + + service.processMessage(channel, msg); + + verify(channel).setFinishHandshake(true); + verify(channel, never()).close(); + } + + @Test + public void startHandshakeSendsHello() { + service.startHandshake(channel); + + verify(channel, times(1)).send(any(HelloMessage.class)); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/business/keepalive/KeepAliveServiceTest.java b/p2p/src/test/java/org/tron/p2p/connection/business/keepalive/KeepAliveServiceTest.java new file mode 100644 index 00000000000..e923afa3f1d --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/business/keepalive/KeepAliveServiceTest.java @@ -0,0 +1,108 @@ +package org.tron.p2p.connection.business.keepalive; + +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.connection.message.base.P2pDisconnectMessage; +import org.tron.p2p.connection.message.keepalive.PingMessage; +import org.tron.p2p.connection.message.keepalive.PongMessage; +import org.tron.p2p.protos.Connect.DisconnectReason; + +/** + * The keep-alive loop is what disconnects a silent peer, so both halves matter: + * answering a ping, and clearing the wait flag when a pong lands. + */ +public class KeepAliveServiceTest { + + private static final InetSocketAddress ADDRESS = + new InetSocketAddress("127.0.0.1", 18888); + + private static class RecordingChannel extends Channel { + final List sent = new ArrayList<>(); + + @Override + public void send(Message message) { + sent.add(message); + } + } + + private P2pConfig saved; + private Map channels; + + private static RecordingChannel channelAt(InetSocketAddress address) throws Exception { + RecordingChannel channel = new RecordingChannel(); + Field field = Channel.class.getDeclaredField("inetSocketAddress"); + field.setAccessible(true); + field.set(channel, address); + return channel; + } + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + Parameter.p2pConfig = new P2pConfig(); + channels = ChannelManager.getChannels(); + channels.clear(); + } + + @After + public void tearDown() { + channels.clear(); + Parameter.p2pConfig = saved; + } + + @Test + public void pingIsAnsweredWithAPong() throws Exception { + RecordingChannel channel = channelAt(ADDRESS); + new KeepAliveService().processMessage(channel, new PingMessage()); + + Assert.assertEquals(1, channel.sent.size()); + Assert.assertEquals(MessageType.KEEP_ALIVE_PONG, channel.sent.get(0).getType()); + } + + @Test + public void pongClearsTheWaitFlagAndRecordsLatency() throws Exception { + RecordingChannel channel = channelAt(ADDRESS); + channel.waitForPong = true; + channel.pingSent = System.currentTimeMillis() - 25; + + new KeepAliveService().processMessage(channel, new PongMessage()); + + Assert.assertFalse(channel.waitForPong); + Assert.assertTrue("latency should have been recorded", channel.getAvgLatency() >= 0); + // A pong is not itself answered. + Assert.assertTrue(channel.sent.isEmpty()); + } + + @Test + public void otherMessageTypesAreIgnored() throws Exception { + RecordingChannel channel = channelAt(ADDRESS); + channel.waitForPong = true; + + new KeepAliveService().processMessage(channel, + new P2pDisconnectMessage(DisconnectReason.PEER_QUITING)); + + Assert.assertTrue(channel.sent.isEmpty()); + Assert.assertTrue("unrelated messages must not clear the wait flag", channel.waitForPong); + } + + @Test + public void closeShutsDownTheScheduler() { + KeepAliveService service = new KeepAliveService(); + service.close(); + // A second close must not throw. + service.close(); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/business/pool/ConnPoolLifecycleTest.java b/p2p/src/test/java/org/tron/p2p/connection/business/pool/ConnPoolLifecycleTest.java new file mode 100644 index 00000000000..6547f9bbee0 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/business/pool/ConnPoolLifecycleTest.java @@ -0,0 +1,133 @@ +package org.tron.p2p.connection.business.pool; + +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.util.List; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; + +/** + * The pool's active/passive bookkeeping. Those two counters drive how many + * outbound slots connect() tries to fill, so a miscount either starves the node + * of peers or makes it dial forever. + */ +public class ConnPoolLifecycleTest { + + private P2pConfig saved; + private ConnPoolService service; + + private static Channel channelAt(String ip, int port, boolean active) throws Exception { + Channel channel = new Channel(); + InetSocketAddress address = new InetSocketAddress(ip, port); + Field socket = Channel.class.getDeclaredField("inetSocketAddress"); + socket.setAccessible(true); + socket.set(channel, address); + Field inet = Channel.class.getDeclaredField("inetAddress"); + inet.setAccessible(true); + inet.set(channel, address.getAddress()); + Field isActive = Channel.class.getDeclaredField("isActive"); + isActive.setAccessible(true); + isActive.set(channel, active); + return channel; + } + + @SuppressWarnings("unchecked") + private List activePeers() throws Exception { + Field field = ConnPoolService.class.getDeclaredField("activePeers"); + field.setAccessible(true); + return (List) field.get(service); + } + + private int counter(String name) throws Exception { + Field field = ConnPoolService.class.getDeclaredField(name); + field.setAccessible(true); + return ((java.util.concurrent.atomic.AtomicInteger) field.get(service)).get(); + } + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + P2pConfig config = new P2pConfig(); + config.setMaxConnections(10); + config.setMaxConnectionsWithSameIp(5); + Parameter.p2pConfig = config; + ChannelManager.getChannels().clear(); + service = new ConnPoolService(); + } + + @After + public void tearDown() { + ChannelManager.getChannels().clear(); + Parameter.p2pConfig = saved; + } + + @Test + public void anOutboundPeerCountsAsActive() throws Exception { + Channel peer = channelAt("127.0.0.1", 10001, true); + service.onConnect(peer); + + Assert.assertEquals(1, activePeers().size()); + Assert.assertEquals(1, counter("activePeersCount")); + Assert.assertEquals(0, counter("passivePeersCount")); + } + + @Test + public void anInboundPeerCountsAsPassive() throws Exception { + Channel peer = channelAt("127.0.0.1", 10001, false); + service.onConnect(peer); + + Assert.assertEquals(1, counter("passivePeersCount")); + Assert.assertEquals(0, counter("activePeersCount")); + } + + @Test + public void connectingTheSamePeerTwiceCountsOnce() throws Exception { + Channel peer = channelAt("127.0.0.1", 10001, true); + service.onConnect(peer); + service.onConnect(peer); + + Assert.assertEquals(1, activePeers().size()); + Assert.assertEquals(1, counter("activePeersCount")); + } + + @Test + public void disconnectReversesTheCount() throws Exception { + Channel active = channelAt("127.0.0.1", 10001, true); + Channel passive = channelAt("127.0.0.2", 10002, false); + service.onConnect(active); + service.onConnect(passive); + + service.onDisconnect(active); + Assert.assertEquals(0, counter("activePeersCount")); + Assert.assertEquals(1, counter("passivePeersCount")); + + service.onDisconnect(passive); + Assert.assertEquals(0, counter("passivePeersCount")); + Assert.assertTrue(activePeers().isEmpty()); + } + + @Test + public void disconnectingAnUnknownPeerIsANoOp() throws Exception { + service.onDisconnect(channelAt("127.0.0.9", 10009, true)); + + Assert.assertEquals(0, counter("activePeersCount")); + Assert.assertEquals(0, counter("passivePeersCount")); + Assert.assertTrue(activePeers().isEmpty()); + } + + @Test + public void onMessageIsInert() throws Exception { + Channel peer = channelAt("127.0.0.1", 10001, true); + service.onConnect(peer); + + service.onMessage(peer, new byte[] {1, 2, 3}); + + Assert.assertEquals(1, activePeers().size()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/business/upgrade/UpgradeControllerTest.java b/p2p/src/test/java/org/tron/p2p/connection/business/upgrade/UpgradeControllerTest.java new file mode 100644 index 00000000000..d8c49bffaac --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/business/upgrade/UpgradeControllerTest.java @@ -0,0 +1,77 @@ +package org.tron.p2p.connection.business.upgrade; + +import java.util.Arrays; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.exception.P2pException.TypeEnum; + +/** + * Compression is negotiated per peer: it applies only when both this node's + * Parameter.version and the peer's advertised version are at least 1. + */ +public class UpgradeControllerTest { + + private static final byte[] COMPRESSIBLE = new byte[4096]; + private int savedVersion; + + @Before + public void setUp() { + savedVersion = Parameter.version; + Arrays.fill(COMPRESSIBLE, (byte) 'a'); + } + + @After + public void tearDown() { + Parameter.version = savedVersion; + } + + @Test + public void legacyPeerGetsUntouchedBytes() throws Exception { + Parameter.version = 1; + byte[] encoded = UpgradeController.codeSendData(0, COMPRESSIBLE); + Assert.assertSame(COMPRESSIBLE, encoded); + Assert.assertSame(COMPRESSIBLE, UpgradeController.decodeReceiveData(0, COMPRESSIBLE)); + } + + @Test + public void legacyLocalVersionGetsUntouchedBytes() throws Exception { + Parameter.version = 0; + Assert.assertSame(COMPRESSIBLE, UpgradeController.codeSendData(1, COMPRESSIBLE)); + Assert.assertSame(COMPRESSIBLE, UpgradeController.decodeReceiveData(1, COMPRESSIBLE)); + } + + @Test + public void upgradedPeerRoundTripsThroughCompression() throws Exception { + Parameter.version = 1; + byte[] encoded = UpgradeController.codeSendData(1, COMPRESSIBLE); + // Highly repetitive input must actually shrink, otherwise the wrapper is + // adding framing for nothing. + Assert.assertTrue(encoded.length < COMPRESSIBLE.length); + Assert.assertArrayEquals(COMPRESSIBLE, UpgradeController.decodeReceiveData(1, encoded)); + } + + @Test + public void incompressiblePayloadStillRoundTrips() throws Exception { + Parameter.version = 1; + byte[] tiny = new byte[] {1, 2, 3}; + byte[] encoded = UpgradeController.codeSendData(1, tiny); + Assert.assertArrayEquals(tiny, UpgradeController.decodeReceiveData(1, encoded)); + } + + @Test + public void malformedFrameBecomesAParseFailure() { + Parameter.version = 1; + try { + UpgradeController.decodeReceiveData(1, new byte[] {(byte) 0xFF, (byte) 0xFF, 0x7F}); + Assert.fail("expected a P2pException"); + } catch (P2pException e) { + Assert.assertEquals(TypeEnum.PARSE_MESSAGE_FAILED, e.getType()); + } catch (Exception e) { + Assert.fail("expected a P2pException, got " + e); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/message/base/P2pDisconnectMessageTest.java b/p2p/src/test/java/org/tron/p2p/connection/message/base/P2pDisconnectMessageTest.java new file mode 100644 index 00000000000..2af14726b09 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/message/base/P2pDisconnectMessageTest.java @@ -0,0 +1,31 @@ +package org.tron.p2p.connection.message.base; + +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.protos.Connect.DisconnectReason; + +public class P2pDisconnectMessageTest { + + @Test + public void roundTripsEveryReason() throws Exception { + for (DisconnectReason reason : DisconnectReason.values()) { + if (reason == DisconnectReason.UNRECOGNIZED) { + continue; + } + P2pDisconnectMessage sent = new P2pDisconnectMessage(reason); + Assert.assertEquals(MessageType.DISCONNECT, sent.getType()); + Assert.assertTrue(sent.valid()); + + P2pDisconnectMessage parsed = new P2pDisconnectMessage(sent.getData()); + Assert.assertTrue("reason should appear in toString for " + reason, + parsed.toString().contains(reason.toString())); + Assert.assertTrue(parsed.valid()); + } + } + + @Test(expected = Exception.class) + public void malformedBytesAreRejected() throws Exception { + new P2pDisconnectMessage(new byte[] {(byte) 0xFF, (byte) 0xFF, 0x7F}); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/message/detect/StatusMessageTest.java b/p2p/src/test/java/org/tron/p2p/connection/message/detect/StatusMessageTest.java new file mode 100644 index 00000000000..60d02345791 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/message/detect/StatusMessageTest.java @@ -0,0 +1,70 @@ +package org.tron.p2p.connection.message.detect; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.connection.message.MessageType; + +/** + * STATUS is the node-detect probe reply. Its remaining-connections figure is + * what ConnPoolService uses to rank candidates, so the arithmetic matters. + */ +public class StatusMessageTest { + + private P2pConfig saved; + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + P2pConfig config = new P2pConfig(); + config.setPort(18888); + config.setIp("127.0.0.1"); + config.setNetworkId(11111); + config.setMaxConnections(30); + Parameter.p2pConfig = config; + ChannelManager.getChannels().clear(); + } + + @After + public void tearDown() { + ChannelManager.getChannels().clear(); + Parameter.p2pConfig = saved; + } + + @Test + public void roundTripsThroughItsWireBytes() throws Exception { + StatusMessage sent = new StatusMessage(); + Assert.assertEquals(MessageType.STATUS, sent.getType()); + Assert.assertTrue(sent.valid()); + + StatusMessage parsed = new StatusMessage(sent.getData()); + Assert.assertEquals(11111, parsed.getNetworkId()); + Assert.assertEquals(sent.getTimestamp(), parsed.getTimestamp()); + Assert.assertEquals("127.0.0.1", parsed.getFrom().getHostV4()); + Assert.assertEquals(18888, parsed.getFrom().getPort()); + Assert.assertTrue(parsed.valid()); + Assert.assertTrue(parsed.toString().startsWith("[StatusMessage")); + } + + @Test + public void remainingConnectionsIsMaxMinusCurrent() throws Exception { + // No channels are registered, so the whole budget is free. + StatusMessage empty = new StatusMessage(new StatusMessage().getData()); + Assert.assertEquals(30, empty.getRemainConnections()); + } + + @Test + public void versionDefaultsToZeroWhenNotSet() throws Exception { + StatusMessage parsed = new StatusMessage(new StatusMessage().getData()); + Assert.assertEquals(0, parsed.getVersion()); + } + + @Test(expected = Exception.class) + public void malformedBytesAreRejected() throws Exception { + new StatusMessage(new byte[] {(byte) 0xFF, (byte) 0xFF, 0x7F}); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/message/handshake/HelloMessageTest.java b/p2p/src/test/java/org/tron/p2p/connection/message/handshake/HelloMessageTest.java new file mode 100644 index 00000000000..41188f570ad --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/message/handshake/HelloMessageTest.java @@ -0,0 +1,33 @@ +package org.tron.p2p.connection.message.handshake; + +import static org.tron.p2p.base.Parameter.p2pConfig; + +import java.util.Arrays; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.connection.business.handshake.DisconnectCode; +import org.tron.p2p.connection.message.MessageType; + +public class HelloMessageTest { + + @Test + public void testHelloMessage() throws Exception { + p2pConfig = new P2pConfig(); + HelloMessage m1 = new HelloMessage(DisconnectCode.NORMAL, 0); + Assert.assertEquals(0, m1.getCode()); + + Assert.assertTrue(Arrays.equals(p2pConfig.getNodeID(), m1.getFrom().getId())); + Assert.assertEquals(p2pConfig.getPort(), m1.getFrom().getPort()); + Assert.assertEquals(p2pConfig.getIp(), m1.getFrom().getHostV4()); + Assert.assertEquals(p2pConfig.getNetworkId(), m1.getNetworkId()); + Assert.assertEquals(MessageType.HANDSHAKE_HELLO, m1.getType()); + + HelloMessage m2 = new HelloMessage(m1.getData()); + Assert.assertTrue(Arrays.equals(p2pConfig.getNodeID(), m2.getFrom().getId())); + Assert.assertEquals(p2pConfig.getPort(), m2.getFrom().getPort()); + Assert.assertEquals(p2pConfig.getIp(), m2.getFrom().getHostV4()); + Assert.assertEquals(p2pConfig.getNetworkId(), m2.getNetworkId()); + Assert.assertEquals(MessageType.HANDSHAKE_HELLO, m2.getType()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/socket/MessageHandlerTest.java b/p2p/src/test/java/org/tron/p2p/connection/socket/MessageHandlerTest.java new file mode 100644 index 00000000000..f76a97bb140 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/socket/MessageHandlerTest.java @@ -0,0 +1,139 @@ +package org.tron.p2p.connection.socket; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.embedded.EmbeddedChannel; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.connection.message.base.P2pDisconnectMessage; +import org.tron.p2p.protos.Connect.DisconnectReason; + +/** + * MessageHandler turns a decode failure into a specific DisconnectReason before + * tearing the channel down. That mapping is what a peer sees when it sends us + * something we cannot read, so each branch is pinned here. + */ +public class MessageHandlerTest { + + private P2pConfig saved; + + /** Captures the disconnect message the handler sends instead of writing it out. */ + private static class RecordingChannel extends Channel { + final List sent = new ArrayList<>(); + final List exceptions = new ArrayList<>(); + + @Override + public void send(Message message) { + sent.add(message); + } + + @Override + public void setChannelHandlerContext(ChannelHandlerContext ctx) { + // EmbeddedChannel's remoteAddress is an EmbeddedSocketAddress, which the + // real implementation casts straight to InetSocketAddress. Keep the ctx + // without the cast so channelActive does not blow up before decode runs. + try { + Field field = Channel.class.getDeclaredField("ctx"); + field.setAccessible(true); + field.set(this, ctx); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + + @Override + public void processException(Throwable throwable) { + exceptions.add(throwable); + } + + DisconnectReason onlyReason() throws Exception { + Assert.assertEquals("expected exactly one message", 1, sent.size()); + Message message = sent.get(0); + Assert.assertEquals(MessageType.DISCONNECT, message.getType()); + P2pDisconnectMessage parsed = new P2pDisconnectMessage(message.getData()); + Field field = P2pDisconnectMessage.class.getDeclaredField("p2pDisconnectMessage"); + field.setAccessible(true); + return ((org.tron.p2p.protos.Connect.P2pDisconnectMessage) field.get(parsed)).getReason(); + } + } + + private static void setAddress(Channel channel) throws Exception { + Field field = Channel.class.getDeclaredField("inetSocketAddress"); + field.setAccessible(true); + field.set(channel, new InetSocketAddress("127.0.0.1", 18888)); + } + + private static RecordingChannel feed(byte[] payload) throws Exception { + RecordingChannel channel = new RecordingChannel(); + setAddress(channel); + EmbeddedChannel netty = new EmbeddedChannel(new MessageHandler(channel)); + netty.writeInbound(Unpooled.wrappedBuffer(payload)); + netty.finishAndReleaseAll(); + return channel; + } + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + P2pConfig config = new P2pConfig(); + config.setPort(18888); + config.setIp("127.0.0.1"); + config.setNetworkId(11111); + Parameter.p2pConfig = config; + } + + @After + public void tearDown() { + Parameter.p2pConfig = saved; + } + + @Test + public void unknownTypeByteMapsToNoSuchMessage() throws Exception { + // 0x80 is MessageType.UNKNOWN and falls through Message.parse's default. + RecordingChannel channel = feed(new byte[] {(byte) 0x80, 1, 2, 3}); + Assert.assertEquals(DisconnectReason.NO_SUCH_MESSAGE, channel.onlyReason()); + Assert.assertEquals(1, channel.exceptions.size()); + } + + @Test + public void unparseableBodyMapsToBadMessage() throws Exception { + // A known type byte with a body protobuf cannot decode. + RecordingChannel channel = feed( + new byte[] {MessageType.KEEP_ALIVE_PING.getType(), (byte) 0xFF, (byte) 0xFF, 0x7F}); + Assert.assertEquals(DisconnectReason.BAD_MESSAGE, channel.onlyReason()); + } + + @Test + public void unregisteredApplicationTypeAlsoMapsToNoSuchMessage() throws Exception { + // data[0] >= 0 routes to handMessage, which looks the byte up in the + // registered handler map rather than going through Message.parse. With no + // handler registered for 0x01 that path raises NO_SUCH_MESSAGE too, so a + // peer probing unused type bytes is disconnected the same way. + RecordingChannel channel = feed(new byte[] {0x01, 1, 2, 3}); + Assert.assertEquals(DisconnectReason.NO_SUCH_MESSAGE, channel.onlyReason()); + } + + @Test + public void exceptionCaughtIsForwardedToTheChannel() throws Exception { + RecordingChannel channel = new RecordingChannel(); + setAddress(channel); + EmbeddedChannel netty = new EmbeddedChannel(new MessageHandler(channel)); + RuntimeException boom = new RuntimeException("boom"); + netty.pipeline().fireExceptionCaught(boom); + netty.finishAndReleaseAll(); + + Assert.assertEquals(1, channel.exceptions.size()); + Assert.assertSame(boom, channel.exceptions.get(0)); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/socket/P2pProtobufVarint32FrameDecoderTest.java b/p2p/src/test/java/org/tron/p2p/connection/socket/P2pProtobufVarint32FrameDecoderTest.java new file mode 100644 index 00000000000..8d87895c602 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/socket/P2pProtobufVarint32FrameDecoderTest.java @@ -0,0 +1,197 @@ +package org.tron.p2p.connection.socket; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.handler.codec.CorruptedFrameException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.tron.p2p.connection.Channel; + +/** + * Covers the varint32 length-prefix decoder that fronts every p2p channel pipeline. + * Framing bugs here corrupt every message on the wire, and the decoder must also be + * safe against partial reads, since TCP can split a frame anywhere. + * + *

    Expected varint encodings below are LEB128 by hand, not taken from the decoder: + * 5 -> 05, 127 -> 7f, 128 -> 80 01, 300 -> ac 02, 16384 -> 80 80 01. + */ +public class P2pProtobufVarint32FrameDecoderTest { + + private static Method readRawVarint32; + + @BeforeClass + public static void init() throws Exception { + readRawVarint32 = P2pProtobufVarint32FrameDecoder.class + .getDeclaredMethod("readRawVarint32", ByteBuf.class); + readRawVarint32.setAccessible(true); + } + + private int readVarint(int... bytes) throws Exception { + byte[] data = new byte[bytes.length]; + for (int i = 0; i < bytes.length; i++) { + data[i] = (byte) bytes[i]; + } + ByteBuf buf = Unpooled.wrappedBuffer(data); + try { + return (Integer) readRawVarint32.invoke(null, buf); + } finally { + buf.release(); + } + } + + @Test + public void readsSingleByteVarints() throws Exception { + Assert.assertEquals(0, readVarint(0x00)); + Assert.assertEquals(5, readVarint(0x05)); + Assert.assertEquals(127, readVarint(0x7f)); + } + + @Test + public void readsMultiByteVarints() throws Exception { + Assert.assertEquals(128, readVarint(0x80, 0x01)); + Assert.assertEquals(300, readVarint(0xac, 0x02)); + Assert.assertEquals(16384, readVarint(0x80, 0x80, 0x01)); + // four- and five-byte forms + Assert.assertEquals(1 << 21, readVarint(0x80, 0x80, 0x80, 0x01)); + Assert.assertEquals(1 << 28, readVarint(0x80, 0x80, 0x80, 0x80, 0x01)); + } + + @Test + public void returnsZeroOnEmptyBuffer() throws Exception { + ByteBuf buf = Unpooled.buffer(0); + try { + Assert.assertEquals(0, ((Integer) readRawVarint32.invoke(null, buf)).intValue()); + } finally { + buf.release(); + } + } + + @Test + public void truncatedVarintYieldsZeroAndRewinds() throws Exception { + // every continuation byte says "more follows" but the buffer ends, so the + // decoder must report 0 and leave the reader index untouched for the next read + for (int len = 1; len <= 4; len++) { + byte[] data = new byte[len]; + for (int i = 0; i < len; i++) { + data[i] = (byte) 0x80; + } + ByteBuf buf = Unpooled.wrappedBuffer(data); + try { + Assert.assertEquals(0, ((Integer) readRawVarint32.invoke(null, buf)).intValue()); + Assert.assertEquals("reader index must be rewound for a truncated varint", + 0, buf.readerIndex()); + } finally { + buf.release(); + } + } + } + + @Test + public void rejectsMalformedFiveByteVarint() throws Exception { + // a fifth byte with the continuation bit still set overflows an int + try { + readVarint(0x80, 0x80, 0x80, 0x80, 0x80); + Assert.fail("expected a malformed varint to be rejected"); + } catch (InvocationTargetException e) { + Assert.assertTrue(e.getCause() instanceof CorruptedFrameException); + } + } + + @Test + public void decodesCompleteFrame() { + EmbeddedChannel ch = new EmbeddedChannel( + new P2pProtobufVarint32FrameDecoder(new Channel())); + try { + byte[] payload = new byte[] {1, 2, 3, 4, 5}; + ByteBuf in = Unpooled.buffer(); + in.writeByte(payload.length); + in.writeBytes(payload); + + Assert.assertTrue(ch.writeInbound(in)); + ByteBuf out = ch.readInbound(); + Assert.assertNotNull(out); + try { + Assert.assertEquals(payload.length, out.readableBytes()); + byte[] got = new byte[out.readableBytes()]; + out.readBytes(got); + Assert.assertArrayEquals(payload, got); + } finally { + out.release(); + } + } finally { + ch.finishAndReleaseAll(); + } + } + + @Test + public void waitsForTheRestOfASplitFrame() { + EmbeddedChannel ch = new EmbeddedChannel( + new P2pProtobufVarint32FrameDecoder(new Channel())); + try { + // length says 5 bytes but only 2 arrive: nothing may be emitted yet + ByteBuf first = Unpooled.buffer(); + first.writeByte(5); + first.writeBytes(new byte[] {1, 2}); + Assert.assertFalse(ch.writeInbound(first)); + Assert.assertNull(ch.readInbound()); + + // the remaining 3 bytes complete the frame + Assert.assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] {3, 4, 5}))); + ByteBuf out = ch.readInbound(); + Assert.assertNotNull(out); + try { + byte[] got = new byte[out.readableBytes()]; + out.readBytes(got); + Assert.assertArrayEquals(new byte[] {1, 2, 3, 4, 5}, got); + } finally { + out.release(); + } + } finally { + ch.finishAndReleaseAll(); + } + } + + @Test + public void emitsNothingForLengthPrefixAlone() { + EmbeddedChannel ch = new EmbeddedChannel( + new P2pProtobufVarint32FrameDecoder(new Channel())); + try { + Assert.assertFalse(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] {5}))); + Assert.assertNull(ch.readInbound()); + } finally { + ch.finishAndReleaseAll(); + } + } + + @Test + public void decodesTwoFramesFromOneBuffer() { + EmbeddedChannel ch = new EmbeddedChannel( + new P2pProtobufVarint32FrameDecoder(new Channel())); + try { + ByteBuf in = Unpooled.buffer(); + in.writeByte(2); + in.writeBytes(new byte[] {1, 2}); + in.writeByte(3); + in.writeBytes(new byte[] {3, 4, 5}); + + Assert.assertTrue(ch.writeInbound(in)); + ByteBuf first = ch.readInbound(); + ByteBuf second = ch.readInbound(); + Assert.assertNotNull(first); + Assert.assertNotNull(second); + try { + Assert.assertEquals(2, first.readableBytes()); + Assert.assertEquals(3, second.readableBytes()); + } finally { + first.release(); + second.release(); + } + } finally { + ch.finishAndReleaseAll(); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/discover/NodeManagerTest.java b/p2p/src/test/java/org/tron/p2p/discover/NodeManagerTest.java new file mode 100644 index 00000000000..3cb13ef509d --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/discover/NodeManagerTest.java @@ -0,0 +1,25 @@ +package org.tron.p2p.discover; + +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; + +public class NodeManagerTest { + @Test + public void testNoSeeds() { + P2pConfig config = new P2pConfig(); + Parameter.p2pConfig = config; + try { + NodeManager.init(); + Thread.sleep(100); + Assert.assertEquals(0, NodeManager.getAllNodes().size()); + Assert.assertEquals(0, NodeManager.getTableNodes().size()); + Assert.assertEquals(0, NodeManager.getConnectableNodes().size()); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + NodeManager.close(); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/discover/NodeTest.java b/p2p/src/test/java/org/tron/p2p/discover/NodeTest.java new file mode 100644 index 00000000000..3d8fdb83f38 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/discover/NodeTest.java @@ -0,0 +1,96 @@ +package org.tron.p2p.discover; + +import java.net.InetSocketAddress; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.utils.NetUtil; + +public class NodeTest { + + @Before + public void init() { + Parameter.p2pConfig = new P2pConfig(); + } + + @Test + public void nodeTest() throws InterruptedException { + Node node1 = new Node(new InetSocketAddress("127.0.0.1", 10001)); + Assert.assertEquals(64, node1.getId().length); + + Node node2 = new Node(NetUtil.getNodeId(), "127.0.0.1", null, 10002); + boolean isDif = node1.equals(node2); + Assert.assertFalse(isDif); + + long lastModifyTime = node1.getUpdateTime(); + Thread.sleep(1); + node1.touch(); + Assert.assertNotEquals(lastModifyTime, node1.getUpdateTime()); + + node1.setP2pVersion(11111); + Assert.assertTrue(node1.isConnectible(11111)); + Assert.assertFalse(node1.isConnectible(11112)); + Node node3 = new Node(NetUtil.getNodeId(), "127.0.0.1", null, 10003, 10004); + node3.setP2pVersion(11111); + Assert.assertFalse(node3.isConnectible(11111)); + } + + @Test + public void hostV6NonLiteralRejectedWithoutDnsTest() { + // A non-literal hostV6 (e.g. an attacker-supplied domain) must be rejected by formatHostV6 + // without performing a blocking DNS lookup. Guard against the I/O-thread DoS regression. + Node node = new Node(NetUtil.getNodeId(), null, + "rnd-" + System.nanoTime() + ".attacker-zone.invalid", 10002); + Assert.assertNull(node.getHostV6()); + } + + @Test + public void ipV4CompatibleTest() { + Parameter.p2pConfig.setIp("127.0.0.1"); + Parameter.p2pConfig.setIpv6(null); + + Node node1 = new Node(NetUtil.getNodeId(), "127.0.0.1", null, 10002); + Assert.assertNotNull(node1.getPreferInetSocketAddress()); + + Node node2 = new Node(NetUtil.getNodeId(), null, "fe80:0:0:0:204:61ff:fe9d:f156", 10002); + Assert.assertNull(node2.getPreferInetSocketAddress()); + + Node node3 = new Node(NetUtil.getNodeId(), "127.0.0.1", "fe80:0:0:0:204:61ff:fe9d:f156", 10002); + Assert.assertNotNull(node3.getPreferInetSocketAddress()); + } + + @Test + public void ipV6CompatibleTest() { + Parameter.p2pConfig.setIp(null); + Parameter.p2pConfig.setIpv6("fe80:0:0:0:204:61ff:fe9d:f157"); + + Node node1 = new Node(NetUtil.getNodeId(), "127.0.0.1", null, 10002); + Assert.assertNull(node1.getPreferInetSocketAddress()); + + Node node2 = new Node(NetUtil.getNodeId(), null, "fe80:0:0:0:204:61ff:fe9d:f156", 10002); + Assert.assertNotNull(node2.getPreferInetSocketAddress()); + + Node node3 = new Node(NetUtil.getNodeId(), "127.0.0.1", "fe80:0:0:0:204:61ff:fe9d:f156", 10002); + Assert.assertNotNull(node3.getPreferInetSocketAddress()); + } + + @Test + public void ipCompatibleTest() { + Parameter.p2pConfig.setIp("127.0.0.1"); + Parameter.p2pConfig.setIpv6("fe80:0:0:0:204:61ff:fe9d:f157"); + + Node node1 = new Node(NetUtil.getNodeId(), "127.0.0.1", null, 10002); + Assert.assertNotNull(node1.getPreferInetSocketAddress()); + + Node node2 = new Node(NetUtil.getNodeId(), null, "fe80:0:0:0:204:61ff:fe9d:f156", 10002); + Assert.assertNotNull(node2.getPreferInetSocketAddress()); + + Node node3 = new Node(NetUtil.getNodeId(), "127.0.0.1", "fe80:0:0:0:204:61ff:fe9d:f156", 10002); + Assert.assertNotNull(node3.getPreferInetSocketAddress()); + + Node node4 = new Node(NetUtil.getNodeId(), null, null, 10002); + Assert.assertNull(node4.getPreferInetSocketAddress()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/discover/message/DiscoverMessageTest.java b/p2p/src/test/java/org/tron/p2p/discover/message/DiscoverMessageTest.java new file mode 100644 index 00000000000..e6faef93b06 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/discover/message/DiscoverMessageTest.java @@ -0,0 +1,128 @@ +package org.tron.p2p.discover.message; + +import java.util.Collections; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.kad.FindNodeMessage; +import org.tron.p2p.discover.message.kad.NeighborsMessage; +import org.tron.p2p.discover.message.kad.PingMessage; +import org.tron.p2p.discover.message.kad.PongMessage; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.utils.NetUtil; + +/** + * Message.parse is the entry point for every inbound discovery datagram, so its + * dispatch table and its two rejection paths are what a hostile packet meets + * first. + */ +public class DiscoverMessageTest { + + private P2pConfig saved; + private Node from; + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + P2pConfig config = new P2pConfig(); + config.setNetworkId(11111); + Parameter.p2pConfig = config; + from = new Node(NetUtil.getNodeId(), "127.0.0.1", null, 18888, 18888); + } + + @After + public void tearDown() { + Parameter.p2pConfig = saved; + } + + @Test + public void parseDispatchesEachKadType() throws Exception { + Node to = new Node(NetUtil.getNodeId(), "127.0.0.2", null, 18889, 18889); + + Assert.assertEquals(MessageType.KAD_PING, + Message.parse(new PingMessage(from, to).getSendData()).getType()); + Assert.assertEquals(MessageType.KAD_PONG, + Message.parse(new PongMessage(from).getSendData()).getType()); + Assert.assertEquals(MessageType.KAD_FIND_NODE, + Message.parse(new FindNodeMessage(from, NetUtil.getNodeId()).getSendData()).getType()); + Assert.assertEquals(MessageType.KAD_NEIGHBORS, + Message.parse(new NeighborsMessage(from, Collections.singletonList(to), 1L) + .getSendData()).getType()); + } + + @Test + public void sendDataPrefixesTheTypeByte() { + PongMessage pong = new PongMessage(from); + byte[] sendData = pong.getSendData(); + + Assert.assertEquals(pong.getData().length + 1, sendData.length); + Assert.assertEquals(MessageType.KAD_PONG.getType(), sendData[0]); + for (int i = 0; i < pong.getData().length; i++) { + Assert.assertEquals(pong.getData()[i], sendData[i + 1]); + } + } + + @Test + public void unknownTypeByteIsRejected() { + try { + Message.parse(new byte[] {0x7F, 1, 2, 3}); + Assert.fail("expected a P2pException"); + } catch (Exception e) { + Assert.assertTrue(e instanceof P2pException); + Assert.assertEquals(P2pException.TypeEnum.NO_SUCH_MESSAGE, + ((P2pException) e).getType()); + } + } + + @Test + public void unparseableBodyIsRejected() { + try { + Message.parse(new byte[] {MessageType.KAD_PING.getType(), (byte) 0xFF, (byte) 0xFF, 0x7F}); + Assert.fail("expected an exception"); + } catch (Exception expected) { + Assert.assertNotNull(expected); + } + } + + /** The concrete kad messages all override toString, so reach the base one directly. */ + private static Message bare(final MessageType type, final byte[] data) { + return new Message(type, data) { + @Override + public boolean valid() { + return true; + } + }; + } + + @Test + public void baseToStringReportsTypeAndLength() { + Message message = bare(MessageType.KAD_PING, new byte[] {1, 2, 3}); + Assert.assertEquals("[Message Type: KAD_PING, len: 3]", message.toString()); + Assert.assertEquals(MessageType.KAD_PING, message.getType()); + Assert.assertArrayEquals(new byte[] {1, 2, 3}, message.getData()); + + // A null payload reports zero rather than throwing. + Assert.assertEquals("[Message Type: KAD_PONG, len: 0]", + bare(MessageType.KAD_PONG, null).toString()); + } + + @Test + public void concreteMessageToStringNamesItsKind() { + Assert.assertTrue(new PongMessage(from).toString().contains("pongMessage")); + } + + @Test + public void messageTypeMapsBytesBothWays() { + for (MessageType type : MessageType.values()) { + if (type == MessageType.UNKNOWN) { + continue; + } + Assert.assertEquals(type, MessageType.fromByte(type.getType())); + } + Assert.assertEquals(MessageType.UNKNOWN, MessageType.fromByte((byte) 0x7F)); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/discover/message/kad/KadMessagesTest.java b/p2p/src/test/java/org/tron/p2p/discover/message/kad/KadMessagesTest.java new file mode 100644 index 00000000000..c85ee9dc106 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/discover/message/kad/KadMessagesTest.java @@ -0,0 +1,158 @@ +package org.tron.p2p.discover.message.kad; + +import com.google.protobuf.ByteString; +import java.util.ArrayList; +import java.util.List; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.MessageType; +import org.tron.p2p.protos.Discover; +import org.tron.p2p.protos.Discover.Endpoint; +import org.tron.p2p.utils.ByteArray; +import org.tron.p2p.utils.NetUtil; + +/** + * Round-trips every kad discovery message through its own wire bytes, which is + * the path a remote datagram takes: build -> toByteArray -> parse. + */ +public class KadMessagesTest { + + private P2pConfig saved; + private Node from; + private Node to; + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + P2pConfig config = new P2pConfig(); + config.setNetworkId(11111); + Parameter.p2pConfig = config; + from = new Node(NetUtil.getNodeId(), "127.0.0.1", null, 18888, 18888); + to = new Node(NetUtil.getNodeId(), "127.0.0.2", null, 18889, 18889); + } + + @After + public void tearDown() { + Parameter.p2pConfig = saved; + } + + @Test + public void pingRoundTrip() throws Exception { + PingMessage sent = new PingMessage(from, to); + Assert.assertEquals(MessageType.KAD_PING, sent.getType()); + Assert.assertTrue(sent.valid()); + + PingMessage parsed = new PingMessage(sent.getData()); + Assert.assertEquals(11111, parsed.getNetworkId()); + Assert.assertArrayEquals(from.getId(), parsed.getFrom().getId()); + Assert.assertEquals("127.0.0.1", parsed.getFrom().getHostV4()); + Assert.assertEquals(18888, parsed.getFrom().getPort()); + Assert.assertEquals("127.0.0.2", parsed.getTo().getHostV4()); + Assert.assertEquals(sent.getTimestamp(), parsed.getTimestamp()); + Assert.assertTrue(parsed.toString().startsWith("[pingMessage")); + } + + @Test + public void pongRoundTrip() throws Exception { + PongMessage sent = new PongMessage(from); + Assert.assertEquals(MessageType.KAD_PONG, sent.getType()); + Assert.assertTrue(sent.valid()); + + PongMessage parsed = new PongMessage(sent.getData()); + Assert.assertEquals(11111, parsed.getNetworkId()); + Assert.assertArrayEquals(from.getId(), parsed.getFrom().getId()); + Assert.assertEquals(sent.getTimestamp(), parsed.getTimestamp()); + Assert.assertNotNull(parsed.toString()); + } + + @Test + public void findNodeRoundTrip() throws Exception { + byte[] target = NetUtil.getNodeId(); + FindNodeMessage sent = new FindNodeMessage(from, target); + Assert.assertEquals(MessageType.KAD_FIND_NODE, sent.getType()); + Assert.assertTrue(sent.valid()); + + FindNodeMessage parsed = new FindNodeMessage(sent.getData()); + Assert.assertArrayEquals(target, parsed.getTargetId()); + Assert.assertArrayEquals(from.getId(), parsed.getFrom().getId()); + Assert.assertEquals(sent.getTimestamp(), parsed.getTimestamp()); + Assert.assertNotNull(parsed.toString()); + } + + @Test + public void neighboursRoundTrip() throws Exception { + List neighbours = new ArrayList<>(); + neighbours.add(to); + neighbours.add(new Node(NetUtil.getNodeId(), "127.0.0.3", null, 18890, 18890)); + + NeighborsMessage sent = new NeighborsMessage(from, neighbours, 42L); + Assert.assertEquals(MessageType.KAD_NEIGHBORS, sent.getType()); + Assert.assertTrue(sent.valid()); + + NeighborsMessage parsed = new NeighborsMessage(sent.getData()); + Assert.assertEquals(2, parsed.getNodes().size()); + Assert.assertArrayEquals(from.getId(), parsed.getFrom().getId()); + Assert.assertEquals(sent.getTimestamp(), parsed.getTimestamp()); + Assert.assertNotNull(parsed.toString()); + } + + @Test + public void neighboursWithNoNodesIsStillValid() throws Exception { + NeighborsMessage sent = + new NeighborsMessage(from, new ArrayList(), 1L); + NeighborsMessage parsed = new NeighborsMessage(sent.getData()); + Assert.assertTrue(parsed.getNodes().isEmpty()); + Assert.assertTrue(parsed.valid()); + } + + @Test + public void endpointCarriesIpv6AndOmitsEmptyFields() { + Node dual = new Node(NetUtil.getNodeId(), "127.0.0.1", "::1", 18888, 18888); + Endpoint endpoint = KadMessage.getEndpointFromNode(dual); + Assert.assertEquals(18888, endpoint.getPort()); + Assert.assertFalse(endpoint.getNodeId().isEmpty()); + Assert.assertFalse(endpoint.getAddress().isEmpty()); + Assert.assertFalse(endpoint.getAddressIpv6().isEmpty()); + + Node v4Only = new Node(NetUtil.getNodeId(), "127.0.0.1", null, 18888, 18888); + Assert.assertTrue(KadMessage.getEndpointFromNode(v4Only).getAddressIpv6().isEmpty()); + } + + @Test + public void aMessageWithNoAddressIsRejected() throws Exception { + // valid() delegates to NetUtil.validNode, which requires a routable host. + // An endpoint carrying only a node id and a port is the shape a malformed + // NEIGHBOURS entry takes, and it must not pass. + Discover.PongMessage wire = Discover.PongMessage.newBuilder() + .setFrom(Endpoint.newBuilder() + .setNodeId(ByteString.copyFrom(NetUtil.getNodeId())) + .setPort(18888) + .build()) + .setEcho(1) + .setTimestamp(System.currentTimeMillis()) + .build(); + + PongMessage parsed = new PongMessage(wire.toByteArray()); + Assert.assertFalse(parsed.valid()); + } + + @Test + public void aMessageWithNoNodeIdIsRejected() throws Exception { + Discover.PongMessage wire = Discover.PongMessage.newBuilder() + .setFrom(Endpoint.newBuilder() + .setAddress(ByteString.copyFrom(ByteArray.fromString("127.0.0.1"))) + .setPort(18888) + .build()) + .setEcho(1) + .setTimestamp(System.currentTimeMillis()) + .build(); + + PongMessage parsed = new PongMessage(wire.toByteArray()); + Assert.assertFalse(parsed.valid()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/KadServiceTest.java b/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/KadServiceTest.java new file mode 100644 index 00000000000..a7189677520 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/KadServiceTest.java @@ -0,0 +1,53 @@ +package org.tron.p2p.discover.protocol.kad; + +import java.net.InetSocketAddress; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.kad.PingMessage; +import org.tron.p2p.discover.socket.UdpEvent; + +public class KadServiceTest { + + private static KadService kadService; + private static Node node1; + private static Node node2; + + @BeforeClass + public static void init() { + Parameter.p2pConfig = new P2pConfig(); + Parameter.p2pConfig.setDiscoverEnable(false); + kadService = new KadService(); + kadService.init(); + KadService.setPingTimeout(300); + node1 = new Node(new InetSocketAddress("127.0.0.1", 22222)); + node2 = new Node(new InetSocketAddress("127.0.0.2", 22222)); + } + + @Test + public void test() { + Assert.assertNotNull(kadService.getPongTimer()); + Assert.assertNotNull(kadService.getPublicHomeNode()); + Assert.assertEquals(0, kadService.getAllNodes().size()); + + NodeHandler nodeHandler = kadService.getNodeHandler(node1); + Assert.assertNotNull(nodeHandler); + Assert.assertEquals(1, kadService.getAllNodes().size()); + + UdpEvent event = new UdpEvent(new PingMessage(node2, kadService.getPublicHomeNode()), + new InetSocketAddress(node2.getHostV4(), node2.getPort())); + kadService.handleEvent(event); + Assert.assertEquals(2, kadService.getAllNodes().size()); + + } + + + @AfterClass + public static void destroy() { + kadService.close(); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/NodeHandlerTest.java b/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/NodeHandlerTest.java new file mode 100644 index 00000000000..59b5a9a3548 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/NodeHandlerTest.java @@ -0,0 +1,114 @@ +package org.tron.p2p.discover.protocol.kad; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.kad.PingMessage; +import org.tron.p2p.discover.message.kad.PongMessage; +import org.tron.p2p.utils.NetUtil; + +public class NodeHandlerTest { + + private static KadService kadService; + private static Node currNode; + private static Node oldNode; + private static Node replaceNode; + private static NodeHandler currHandler; + private static NodeHandler oldHandler; + private static NodeHandler replaceHandler; + + @BeforeClass + public static void init() { + Parameter.p2pConfig = new P2pConfig(); + Parameter.p2pConfig.setDiscoverEnable(false); + kadService = new KadService(); + kadService.init(); + KadService.setPingTimeout(300); + currNode = new Node(new InetSocketAddress("127.0.0.1", 22222)); + oldNode = new Node(new InetSocketAddress("127.0.0.2", 22222)); + replaceNode = new Node(new InetSocketAddress("127.0.0.3", 22222)); + currHandler = new NodeHandler(currNode, kadService); + oldHandler = new NodeHandler(oldNode, kadService); + replaceHandler = new NodeHandler(replaceNode, kadService); + } + + @Test + public void test() throws InterruptedException { + Assert.assertEquals(NodeHandler.State.DISCOVERED, currHandler.getState()); + Assert.assertEquals(NodeHandler.State.DISCOVERED, oldHandler.getState()); + Assert.assertEquals(NodeHandler.State.DISCOVERED, replaceHandler.getState()); + Thread.sleep(2000); + Assert.assertEquals(NodeHandler.State.DEAD, currHandler.getState()); + Assert.assertEquals(NodeHandler.State.DEAD, oldHandler.getState()); + Assert.assertEquals(NodeHandler.State.DEAD, replaceHandler.getState()); + + PingMessage msg = new PingMessage(currNode, kadService.getPublicHomeNode()); + currHandler.handlePing(msg); + Assert.assertEquals(NodeHandler.State.DISCOVERED, currHandler.getState()); + PongMessage msg1 = new PongMessage(currNode); + currHandler.handlePong(msg1); + Assert.assertEquals(NodeHandler.State.ACTIVE, currHandler.getState()); + Assert.assertTrue(kadService.getTable().contains(currNode)); + kadService.getTable().dropNode(currNode); + } + + @Test + public void testChangeState() throws Exception { + currHandler.changeState(NodeHandler.State.ALIVE); + Assert.assertEquals(NodeHandler.State.ACTIVE, currHandler.getState()); + Assert.assertTrue(kadService.getTable().contains(currNode)); + + Class clazz = NodeHandler.class; + Constructor cn = clazz.getDeclaredConstructor(Node.class, KadService.class); + NodeHandler nh = cn.newInstance(oldNode, kadService); + Field declaredField = clazz.getDeclaredField("replaceCandidate"); + declaredField.setAccessible(true); + declaredField.set(nh, replaceHandler); + + kadService.getTable().addNode(oldNode); + nh.changeState(NodeHandler.State.EVICTCANDIDATE); + nh.changeState(NodeHandler.State.DEAD); + replaceHandler.changeState(NodeHandler.State.ALIVE); + + Assert.assertFalse(kadService.getTable().contains(oldNode)); + Assert.assertTrue(kadService.getTable().contains(replaceNode)); + } + + @Test + public void testSendFindNode() throws Exception { + byte[] nodeId = NetUtil.getNodeId(); + Node node = new Node(nodeId, "127.0.0.1", "", 1); + NodeHandler handler = new NodeHandler(node, kadService); + + kadService.getTable().addNode(node); + + for (int i = 0; i < 2; i++) { + String ip = "127.0.1." + i; + kadService.getTable().addNode(new Node(nodeId, ip, "", 1)); + } + + for (int i = 0; i < 6; i++) { + handler.sendFindNode(NetUtil.getNodeId()); + } + + Assert.assertFalse(handler.getState().equals(NodeHandler.State.DEAD)); + + kadService.getTable().addNode(new Node(nodeId, "127.0.1.4", "", 1)); + + handler.sendFindNode(NetUtil.getNodeId()); + + Assert.assertTrue(handler.getState().equals(NodeHandler.State.DEAD)); + } + + @AfterClass + public static void destroy() { + kadService.close(); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/table/NodeEntryTest.java b/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/table/NodeEntryTest.java new file mode 100644 index 00000000000..fcc1d4f0318 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/table/NodeEntryTest.java @@ -0,0 +1,69 @@ +package org.tron.p2p.discover.protocol.kad.table; + +import java.net.InetSocketAddress; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.discover.Node; +import org.tron.p2p.utils.ByteArray; +import org.tron.p2p.utils.NetUtil; + +public class NodeEntryTest { + @Test + public void test() throws InterruptedException { + Node node1 = new Node(new InetSocketAddress("127.0.0.1", 10001)); + NodeEntry nodeEntry = new NodeEntry(NetUtil.getNodeId(), node1); + + long lastModified = nodeEntry.getModified(); + Thread.sleep(1); + nodeEntry.touch(); + long nowModified = nodeEntry.getModified(); + Assert.assertNotEquals(lastModified, nowModified); + + Node node2 = new Node(new InetSocketAddress("127.0.0.1", 10002)); + NodeEntry nodeEntry2 = new NodeEntry(NetUtil.getNodeId(), node2); + boolean isDif = nodeEntry.equals(nodeEntry2); + Assert.assertTrue(isDif); + } + + @Test + public void testDistance() { + byte[] randomId = NetUtil.getNodeId(); + String hexRandomIdStr = ByteArray.toHexString(randomId); + Assert.assertEquals(128, hexRandomIdStr.length()); + + byte[] nodeId1 = ByteArray.fromHexString( + "0000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000"); + byte[] nodeId2 = ByteArray.fromHexString( + "a000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000"); + Assert.assertEquals(17, NodeEntry.distance(nodeId1, nodeId2)); + + byte[] nodeId3 = ByteArray.fromHexString( + "0000800000000000000000000000000000000000000000000000000000000001" + + "0000000000000000000000000000000000000000000000000000000000000000"); + Assert.assertEquals(1, NodeEntry.distance(nodeId1, nodeId3)); + + byte[] nodeId4 = ByteArray.fromHexString( + "0000400000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000"); + Assert.assertEquals(0, NodeEntry.distance(nodeId1, nodeId4)); // => 0 + + byte[] nodeId5 = ByteArray.fromHexString( + "0000200000000000000000000000000000000000000000000000000000000000" + + "4000000000000000000000000000000000000000000000000000000000000000"); + Assert.assertEquals(-1, NodeEntry.distance(nodeId1, nodeId5)); // => 0 + + byte[] nodeId6 = ByteArray.fromHexString( + "0000100000000000000000000000000000000000000000000000000000000000" + + "2000000000000000000000000000000000000000000000000000000000000000"); + Assert.assertEquals(-2, NodeEntry.distance(nodeId1, nodeId6)); // => 0 + + byte[] nodeId7 = ByteArray.fromHexString( + "0000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000001"); + Assert.assertEquals(-494, NodeEntry.distance(nodeId1, nodeId7)); // => 0 + + Assert.assertEquals(-495, NodeEntry.distance(nodeId1, nodeId1)); // => 0 + } +} diff --git a/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/table/NodeTableTest.java b/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/table/NodeTableTest.java new file mode 100644 index 00000000000..b4fd7259946 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/table/NodeTableTest.java @@ -0,0 +1,225 @@ +package org.tron.p2p.discover.protocol.kad.table; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.Node; +import org.tron.p2p.utils.NetUtil; + +public class NodeTableTest { + + private Node homeNode; + private NodeTable nodeTable; + private String[] ips; + private List ids; + private P2pConfig savedConfig; + + @Test + public void test() { + Node node1 = new Node(new InetSocketAddress("127.0.0.1", 10002)); + + NodeTable table = new NodeTable(node1); + Node nodeTemp = table.getNode(); + Assert.assertEquals(10002, nodeTemp.getPort()); + Assert.assertEquals(0, table.getNodesCount()); + Assert.assertEquals(0, table.getBucketsCount()); + + Node node2 = new Node(new InetSocketAddress("127.0.0.2", 10003)); + Node node3 = new Node(new InetSocketAddress("127.0.0.3", 10004)); + table.addNode(node2); + table.addNode(node3); + int bucketsCount = table.getBucketsCount(); + int nodeCount = table.getNodesCount(); + Assert.assertEquals(2, nodeCount); + Assert.assertTrue(bucketsCount > 0); + + boolean isExist = table.contains(node2); + table.touchNode(node2); + Assert.assertTrue(isExist); + + byte[] targetId = NetUtil.getNodeId(); + List nodeList = table.getClosestNodes(targetId); + Assert.assertFalse(nodeList.isEmpty()); + } + + /** + * init nodes for test. + */ + @Before + public void init() { + // NodeTable.addNode reaches Parameter.p2pConfig.getIp(). This class used to + // rely on some earlier test class in the same fork having set it, so it + // could not run on its own and its result depended on fork scheduling. + savedConfig = Parameter.p2pConfig; + P2pConfig config = new P2pConfig(); + config.setIp("127.0.0.1"); + config.setPort(18888); + Parameter.p2pConfig = config; + + ids = new ArrayList<>(); + for (int i = 0; i < KademliaOptions.BUCKET_SIZE + 1; i++) { + byte[] id = new byte[64]; + id[0] = 17; + id[1] = 16; + if (i < 10) { + id[63] = (byte) i; + } else { + id[62] = 1; + id[63] = (byte) (i - 10); + } + ids.add(id); + } + + ips = new String[KademliaOptions.BUCKET_SIZE + 1]; + byte[] homeId = new byte[64]; + homeNode = new Node(homeId, "127.0.0.1", null, 18888, 18888); + nodeTable = new NodeTable(homeNode); + ips[0] = "127.0.0.2"; + ips[1] = "127.0.0.3"; + ips[2] = "127.0.0.4"; + ips[3] = "127.0.0.5"; + ips[4] = "127.0.0.6"; + ips[5] = "127.0.0.7"; + ips[6] = "127.0.0.8"; + ips[7] = "127.0.0.9"; + ips[8] = "127.0.0.10"; + ips[9] = "127.0.0.11"; + ips[10] = "127.0.0.12"; + ips[11] = "127.0.0.13"; + ips[12] = "127.0.0.14"; + ips[13] = "127.0.0.15"; + ips[14] = "127.0.0.16"; + ips[15] = "127.0.0.17"; + ips[16] = "127.0.0.18"; + } + + @Test + public void addNodeTest() { + Node node = new Node(ids.get(0), ips[0], null, 18888, 18888); + Assert.assertEquals(0, nodeTable.getNodesCount()); + nodeTable.addNode(node); + Assert.assertEquals(1, nodeTable.getNodesCount()); + Assert.assertTrue(nodeTable.contains(node)); + } + + @Test + public void addDupNodeTest() throws Exception { + Node node = new Node(ids.get(0), ips[0], null, 18888, 18888); + nodeTable.addNode(node); + long firstTouchTime = nodeTable.getAllNodes().get(0).getModified(); + TimeUnit.MILLISECONDS.sleep(20); + nodeTable.addNode(node); + long lastTouchTime = nodeTable.getAllNodes().get(0).getModified(); + Assert.assertTrue(lastTouchTime > firstTouchTime); + Assert.assertEquals(1, nodeTable.getNodesCount()); + } + + @Test + public void addNode_bucketFullTest() throws Exception { + for (int i = 0; i < KademliaOptions.BUCKET_SIZE; i++) { + TimeUnit.MILLISECONDS.sleep(10); + addNode(new Node(ids.get(i), ips[i], null, 18888, 18888)); + } + Node lastSeen = nodeTable.addNode(new Node(ids.get(16), ips[16], null, 18888, 18888)); + Assert.assertTrue(null != lastSeen); + Assert.assertEquals(ips[15], lastSeen.getHostV4()); + } + + public void addNode(Node n) { + nodeTable.addNode(n); + } + + @Test + public void dropNodeTest() { + Node node = new Node(ids.get(0), ips[0], null, 18888, 18888); + nodeTable.addNode(node); + Assert.assertTrue(nodeTable.contains(node)); + nodeTable.dropNode(node); + Assert.assertTrue(!nodeTable.contains(node)); + nodeTable.addNode(node); + nodeTable.dropNode(new Node(ids.get(1), ips[0], null, 10000, 10000)); + Assert.assertTrue(!nodeTable.contains(node)); + } + + @Test + public void getBucketsCountTest() { + Assert.assertEquals(0, nodeTable.getBucketsCount()); + Node node = new Node(ids.get(0), ips[0], null, 18888, 18888); + nodeTable.addNode(node); + Assert.assertEquals(1, nodeTable.getBucketsCount()); + } + + @Test + public void touchNodeTest() throws Exception { + Node node = new Node(ids.get(0), ips[0], null, 18888, 18888); + nodeTable.addNode(node); + long firstTouchTime = nodeTable.getAllNodes().get(0).getModified(); + TimeUnit.MILLISECONDS.sleep(10); + nodeTable.touchNode(node); + long lastTouchTime = nodeTable.getAllNodes().get(0).getModified(); + Assert.assertTrue(firstTouchTime < lastTouchTime); + } + + @Test + public void containsTest() { + Node node = new Node(ids.get(0), ips[0], null, 18888, 18888); + Assert.assertTrue(!nodeTable.contains(node)); + nodeTable.addNode(node); + Assert.assertTrue(nodeTable.contains(node)); + } + + @Test + public void getBuckIdTest() { + Node node = new Node(ids.get(0), ips[0], null, 18888, 18888); //id: 11100...000 + nodeTable.addNode(node); + NodeEntry nodeEntry = new NodeEntry(homeNode.getId(), node); + Assert.assertEquals(13, nodeTable.getBucketId(nodeEntry)); + } + + @Test + public void getClosestNodes_nodesMoreThanBucketCapacity() throws Exception { + // Each node needs its own id array: Node keeps the reference it is given + // (this.id = id), so mutating one array after construction would rewrite the + // id of the node already built from it, leaving both nodes with the same id. + byte[] nearId = new byte[64]; + nearId[0] = 15; + Node nearNode = new Node(nearId, "127.0.0.19", null, 18888, 18888); + byte[] farId = new byte[64]; + farId[0] = 70; + Node farNode = new Node(farId, "127.0.0.20", null, 18888, 18888); + nodeTable.addNode(nearNode); + nodeTable.addNode(farNode); + for (int i = 0; i < KademliaOptions.BUCKET_SIZE - 1; i++) { + //To control totally 17 nodes, however closest's capacity is 16 + nodeTable.addNode(new Node(ids.get(i), ips[i], null, 18888, 18888)); + TimeUnit.MILLISECONDS.sleep(10); + } + Assert.assertTrue(nodeTable.getBucketsCount() > 1); + //3 buckets, nearnode's distance is 252, far's is 255, others' are 253 + List closest = nodeTable.getClosestNodes(homeNode.getId()); + Assert.assertEquals(KademliaOptions.BUCKET_SIZE, closest.size()); + Assert.assertTrue(closest.contains(nearNode)); + //the farest node should be excluded + Assert.assertFalse(closest.contains(farNode)); + } + + @Test + public void getClosestNodes_isDiscoverNode() { + Node node = new Node(ids.get(0), ips[0], null, 18888); + nodeTable.addNode(node); + List closest = nodeTable.getClosestNodes(homeNode.getId()); + Assert.assertFalse(closest.isEmpty()); + } + + @After + public void restoreConfig() { + Parameter.p2pConfig = savedConfig; + } +} diff --git a/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/table/TimeComparatorTest.java b/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/table/TimeComparatorTest.java new file mode 100644 index 00000000000..26441a179a1 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/discover/protocol/kad/table/TimeComparatorTest.java @@ -0,0 +1,22 @@ +package org.tron.p2p.discover.protocol.kad.table; + +import java.net.InetSocketAddress; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.discover.Node; +import org.tron.p2p.utils.NetUtil; + +public class TimeComparatorTest { + @Test + public void test() throws InterruptedException { + Node node1 = new Node(new InetSocketAddress("127.0.0.1", 10001)); + NodeEntry ne1 = new NodeEntry(NetUtil.getNodeId(), node1); + Thread.sleep(1); + Node node2 = new Node(new InetSocketAddress("127.0.0.1", 10002)); + NodeEntry ne2 = new NodeEntry(NetUtil.getNodeId(), node2); + TimeComparator tc = new TimeComparator(); + int result = tc.compare(ne1, ne2); + Assert.assertEquals(1, result); + + } +} diff --git a/p2p/src/test/java/org/tron/p2p/discover/socket/P2pPacketDecoderTest.java b/p2p/src/test/java/org/tron/p2p/discover/socket/P2pPacketDecoderTest.java new file mode 100644 index 00000000000..ae4fc6bada7 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/discover/socket/P2pPacketDecoderTest.java @@ -0,0 +1,121 @@ +package org.tron.p2p.discover.socket; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.channel.socket.DatagramPacket; +import java.net.InetSocketAddress; +import java.util.Collections; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.message.MessageType; +import org.tron.p2p.discover.message.kad.NeighborsMessage; +import org.tron.p2p.discover.message.kad.PingMessage; +import org.tron.p2p.discover.message.kad.PongMessage; +import org.tron.p2p.utils.NetUtil; + +/** + * Every inbound discovery datagram lands here first. A remote peer controls the + * bytes entirely, so the decoder has to swallow anything malformed rather than + * let it escape up the pipeline. + */ +public class P2pPacketDecoderTest { + + private static final InetSocketAddress SENDER = + new InetSocketAddress("127.0.0.1", 18888); + private static final InetSocketAddress RECIPIENT = + new InetSocketAddress("127.0.0.2", 18889); + + private P2pConfig saved; + private Node from; + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + P2pConfig config = new P2pConfig(); + config.setNetworkId(11111); + Parameter.p2pConfig = config; + from = new Node(NetUtil.getNodeId(), "127.0.0.1", null, 18888, 18888); + } + + @After + public void tearDown() { + Parameter.p2pConfig = saved; + } + + private static EmbeddedChannel channel() { + return new EmbeddedChannel(new P2pPacketDecoder(), new ChannelInboundHandlerAdapter()); + } + + private static Object decode(byte[] wire) { + EmbeddedChannel channel = channel(); + channel.writeInbound(new DatagramPacket(Unpooled.copiedBuffer(wire), RECIPIENT, SENDER)); + Object out = channel.readInbound(); + channel.finishAndReleaseAll(); + return out; + } + + @Test + public void wellFormedPingBecomesAUdpEvent() { + Node to = new Node(NetUtil.getNodeId(), "127.0.0.2", null, 18889, 18889); + Object out = decode(new PingMessage(from, to).getSendData()); + + Assert.assertTrue(out instanceof UdpEvent); + UdpEvent event = (UdpEvent) out; + Assert.assertEquals(MessageType.KAD_PING, event.getMessage().getType()); + Assert.assertEquals(SENDER, event.getAddress()); + } + + @Test + public void neighboursAndPongAlsoDecode() { + Node to = new Node(NetUtil.getNodeId(), "127.0.0.2", null, 18889, 18889); + Assert.assertTrue(decode(new PongMessage(from).getSendData()) instanceof UdpEvent); + Assert.assertTrue(decode( + new NeighborsMessage(from, Collections.singletonList(to), 1L).getSendData()) + instanceof UdpEvent); + } + + @Test + public void tooShortPacketsAreDropped() { + // length <= 1 is rejected before any parse is attempted. + Assert.assertNull(decode(new byte[0])); + Assert.assertNull(decode(new byte[] {MessageType.KAD_PING.getType()})); + } + + @Test + public void oversizedPacketsAreDropped() { + // MAXSIZE is 2048 and the check is >=, so 2048 bytes is already too big. + byte[] huge = new byte[2048]; + huge[0] = MessageType.KAD_PING.getType(); + Assert.assertNull(decode(huge)); + } + + @Test + public void unknownTypeByteIsSwallowed() { + // Message.parse raises NO_SUCH_MESSAGE; the decoder must absorb it rather + // than let it reach the handler and tear the shared socket down. + Assert.assertNull(decode(new byte[] {0x7F, 1, 2, 3})); + } + + @Test + public void unparseableBodyIsSwallowed() { + Assert.assertNull(decode( + new byte[] {MessageType.KAD_PING.getType(), (byte) 0xFF, (byte) 0xFF, 0x7F})); + } + + @Test + public void aBadPacketDoesNotCloseTheChannel() { + EmbeddedChannel channel = channel(); + channel.writeInbound(new DatagramPacket( + Unpooled.copiedBuffer(new byte[] {0x7F, 1, 2, 3}), RECIPIENT, SENDER)); + + Assert.assertTrue("the discovery socket is shared; one bad datagram must not close it", + channel.isOpen()); + channel.finishAndReleaseAll(); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/AlgorithmTest.java b/p2p/src/test/java/org/tron/p2p/dns/AlgorithmTest.java new file mode 100644 index 00000000000..2f2faf2404c --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/AlgorithmTest.java @@ -0,0 +1,110 @@ +package org.tron.p2p.dns; + +import com.google.protobuf.ByteString; +import java.math.BigInteger; +import java.security.SignatureException; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.dns.tree.Algorithm; +import org.tron.p2p.protos.Discover.DnsRoot.TreeRoot; +import org.tron.p2p.utils.ByteArray; + +public class AlgorithmTest { + + public static String privateKey = "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f" + + "291"; + + @Test + public void testPublicKeyCompressAndUnCompress() { + BigInteger publicKeyInt = Algorithm.generateKeyPair(privateKey).getPublicKey(); + + String publicKey = ByteArray.toHexString(publicKeyInt.toByteArray()); + String pubKeyCompressHex = Algorithm.compressPubKey(publicKeyInt); + String base32PubKey = Algorithm.encode32(ByteArray.fromHexString(pubKeyCompressHex)); + Assert.assertEquals("APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ", base32PubKey); + String unCompressPubKey = Algorithm.decompressPubKey(pubKeyCompressHex); + Assert.assertEquals(publicKey, unCompressPubKey); + } + + @Test + public void testSignatureAndVerify() { + BigInteger publicKeyInt = Algorithm.generateKeyPair(privateKey).getPublicKey(); + String publicKey = ByteArray.toHexString(publicKeyInt.toByteArray()); + + String msg = "Message for signing"; + byte[] sig = Algorithm.sigData(msg, privateKey); + try { + Assert.assertTrue(Algorithm.verifySignature(publicKey, msg, sig)); + } catch (SignatureException e) { + Assert.fail(); + } + } + + @Test + public void testEncode32() { + String content = "tree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.examp" + + "le.org"; + String base32 = Algorithm.encode32(content.getBytes()); + Assert.assertArrayEquals(content.getBytes(), Algorithm.decode32(base32)); + + Assert.assertEquals("USBZA4IGXFNVDBBQACEK3FGLWM", Algorithm.encode32AndTruncate(content)); + } + + @Test + public void testValidHash() { + Assert.assertTrue(Algorithm.isValidHash("C7HRFPF3BLGF3YR4DY5KX3SMBE")); + Assert.assertFalse(Algorithm.isValidHash("C7HRFPF3BLGF3YR4DY5KX3SMBE======")); + } + + @Test + public void testEncode64() { + String base64Sig = "1eFfi7ggzTbtAldC1pfXPn5A3mZQwEdk0-ZwCKGhZbQn2E6zWodG7v06kFu8gjiCe6FvJo04BY" + + "vgKHtPJ5pX5wE"; + byte[] decoded; + try { + decoded = Algorithm.decode64(base64Sig); + Assert.assertEquals(base64Sig, Algorithm.encode64(decoded)); + } catch (Exception e) { + Assert.fail(); + } + + String base64Content = "1eFfi7ggzTbtAldC1pfXPn5A3mZQwEdk0-ZwCKGhZbQn2E6zWodG7v06kFu8gjiCe6FvJo" + + "04BYvgKHtPJ5pX5wE="; + decoded = Algorithm.decode64(base64Content); + Assert.assertNotEquals(base64Content, Algorithm.encode64(decoded)); + } + + @Test + public void testRecoverPublicKey() { + TreeRoot.Builder builder = TreeRoot.newBuilder(); + builder.setERoot(ByteString.copyFrom("VXJIDGQECCIIYNY3GZEJSFSG6U".getBytes())); + builder.setLRoot(ByteString.copyFrom("FDXN3SN67NA5DKA4J2GOK7BVQI".getBytes())); + builder.setSeq(3447); + + //String eth_msg = "enrtree-root:v1 e=VXJIDGQECCIIYNY3GZEJSFSG6U" + // + " l=FDXN3SN67NA5DKA4J2GOK7BVQI seq=3447"; + String msg = builder.toString(); + byte[] sig = Algorithm.sigData(builder.toString(), privateKey); + Assert.assertEquals(65, sig.length); + String base64Sig = Algorithm.encode64(sig); + Assert.assertEquals( + "_Zfgv2g7IUzjhqkMGCPZuPT_HAA01hTxiKAa3D1dyokk8_OKee-Jy2dSNo-nqEr6WOFkxv3A9ukYuiJRsf2v8hs", + base64Sig); + + byte[] sigData; + try { + sigData = Algorithm.decode64(base64Sig); + Assert.assertArrayEquals(sig, sigData); + } catch (Exception e) { + Assert.fail(); + } + + BigInteger publicKeyInt = Algorithm.generateKeyPair(privateKey).getPublicKey(); + try { + BigInteger recoverPublicKeyInt = Algorithm.recoverPublicKey(msg, sig); + Assert.assertEquals(publicKeyInt, recoverPublicKeyInt); + } catch (SignatureException e) { + Assert.fail(); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/AwsRoute53Test.java b/p2p/src/test/java/org/tron/p2p/dns/AwsRoute53Test.java new file mode 100644 index 00000000000..d1cb816fc42 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/AwsRoute53Test.java @@ -0,0 +1,169 @@ +package org.tron.p2p.dns; + +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.dns.tree.Tree; +import org.tron.p2p.dns.update.AwsClient; +import org.tron.p2p.dns.update.AwsClient.RecordSet; +import org.tron.p2p.dns.update.PublishConfig; +import org.tron.p2p.exception.DnsException; +import software.amazon.awssdk.services.route53.model.Change; +import software.amazon.awssdk.services.route53.model.ChangeAction; + +public class AwsRoute53Test { + + @Test + public void testChangeSort() { + + Map existing = new HashMap<>(); + existing.put("n", new RecordSet(new String[] { + "tree-root-v1:CjoKGlVKQU9JQlMyUFlZMjJYUU1WRlNXT1RZSlhVEhpGRFhOM1NONjdOQTVES0E0SjJHT0s3QlZ" + + "RSRgIEldBTE5aWHEyRkk5Ui1ubjdHQk9HdWJBRFVPakZ2MWp5TjZiUHJtSWNTNks0ZE0wc1dKMUwzT2paW" + + "FRGei1KcldDenZZVHJId2RMSTlUczRPZ2Q4TXlJUnM"}, + AwsClient.rootTTL)); + existing.put("2kfjogvxdqtxxugbh7gs7naaai.n", new RecordSet(new String[] { + "nodes:-HW4QO1ml1DdXLeZLsUxewnthhUy8eROqkDyoMTyavfks9JlYQIlMFEUoM78PovJDPQrAkrb3LRJ-", + "vtrymDguKCOIAWAgmlkgnY0iXNlY3AyNTZrMaEDffaGfJzgGhUif1JqFruZlYmA31HzathLSWxfbq_QoQ4"}, + 3333)); + existing.put("fdxn3sn67na5dka4j2gok7bvqi.n", + new RecordSet(new String[] {"tree-branch:"}, AwsClient.treeNodeTTL)); + + Map newRecords = new HashMap<>(); + newRecords.put("n", + "tree-root-v1:CjoKGkZEWE4zU042N05BNURLQTRKMkdPSzdCVlFJEhpGRFhOM1NONjdOQTVES0E0SjJHT0s3QlZ" + + "RSRgJElc5aDU4d1cyajUzdlBMeHNBSGN1cDMtV0ZEM2lvZUk4SkJrZkdYSk93dmI0R0lHR01pQVAxRkJVV" + + "Gc4bHlORERleXJkck9uSDdSbUNUUnJRVGxqUm9UaHM"); + newRecords.put("c7hrfpf3blgf3yr4dy5kx3smbe.n", + "tree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org"); + newRecords.put("jwxydbpxywg6fx3gmdibfa6cj4.n", + "tree-branch:2XS2367YHAXJFGLZHVAWLQD4ZY,H4FHT4B454P6UXFD7JCYQ5PWDY,MHTDO6TMUBRIA2XWG5LUDA" + + "CK24"); + newRecords.put("2xs2367yhaxjfglzhvawlqd4zy.n", + "nodes:-HW4QOFzoVLaFJnNhbgMoDXPnOvcdVuj7pDpqRvh6BRDO68aVi5ZcjB3vzQRZH2IcLBGHzo8uUN3snqmgT" + + "iE56CH3AMBgmlkgnY0iXNlY3AyNTZrMaECC2_24YYkYHEgdzxlSNKQEnHhuNAbNlMlWJxrJxbAFvA"); + newRecords.put("h4fht4b454p6uxfd7jcyq5pwdy.n", + "nodes:-HW4QAggRauloj2SDLtIHN1XBkvhFZ1vtf1raYQp9TBW2RD5EEawDzbtSmlXUfnaHcvwOizhVYLtr7e6vw" + + "7NAf6mTuoCgmlkgnY0iXNlY3AyNTZrMaECjrXI8TLNXU0f8cthpAMxEshUyQlK-AM0PW2wfrnacNI"); + newRecords.put("mhtdo6tmubria2xwg5ludack24.n", + "nodes:-HW4QLAYqmrwllBEnzWWs7I5Ev2IAs7x_dZlbYdRdMUx5EyKHDXp7AV5CkuPGUPdvbv1_Ms1CPfhcGCvSE" + + "lSosZmyoqAgmlkgnY0iXNlY3AyNTZrMaECriawHKWdDRk2xeZkrOXBQ0dfMFLHY4eENZwdufn1S1o"); + + AwsClient publish; + try { + publish = new AwsClient("random1", "random2", "random3", + "us-east-1", new P2pConfig().getPublishConfig().getChangeThreshold()); + } catch (DnsException e) { + Assert.fail(); + return; + } + List changes = publish.computeChanges("n", newRecords, existing); + + Change[] wantChanges = new Change[] { + publish.newTXTChange(ChangeAction.CREATE, "2xs2367yhaxjfglzhvawlqd4zy.n", + AwsClient.treeNodeTTL, + "\"nodes:-HW4QOFzoVLaFJnNhbgMoDXPnOvcdVuj7pDpqRvh6BRDO68aVi5ZcjB3vzQRZH2IcLBGHzo8uUN3" + + "snqmgTiE56CH3AMBgmlkgnY0iXNlY3AyNTZrMaECC2_24YYkYHEgdzxlSNKQEnHhuNAbNlMlWJxrJx" + + "bAFvA\""), + publish.newTXTChange(ChangeAction.CREATE, "c7hrfpf3blgf3yr4dy5kx3smbe.n", + AwsClient.treeNodeTTL, + "\"tree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@morenodes.example.org" + + "\""), + publish.newTXTChange(ChangeAction.CREATE, "h4fht4b454p6uxfd7jcyq5pwdy.n", + AwsClient.treeNodeTTL, + "\"nodes:-HW4QAggRauloj2SDLtIHN1XBkvhFZ1vtf1raYQp9TBW2RD5EEawDzbtSmlXUfnaHcvwOizhVYLt" + + "r7e6vw7NAf6mTuoCgmlkgnY0iXNlY3AyNTZrMaECjrXI8TLNXU0f8cthpAMxEshUyQlK-AM0PW2wfr" + + "nacNI\""), + publish.newTXTChange(ChangeAction.CREATE, "jwxydbpxywg6fx3gmdibfa6cj4.n", + AwsClient.treeNodeTTL, + "\"tree-branch:2XS2367YHAXJFGLZHVAWLQD4ZY,H4FHT4B454P6UXFD7JCYQ5PWDY,MHTDO6TMUBRIA2XW" + + "G5LUDACK24\""), + publish.newTXTChange(ChangeAction.CREATE, "mhtdo6tmubria2xwg5ludack24.n", + AwsClient.treeNodeTTL, + "\"nodes:-HW4QLAYqmrwllBEnzWWs7I5Ev2IAs7x_dZlbYdRdMUx5EyKHDXp7AV5CkuPGUPdvbv1_Ms1CPfh" + + "cGCvSElSosZmyoqAgmlkgnY0iXNlY3AyNTZrMaECriawHKWdDRk2xeZkrOXBQ0dfMFLHY4eENZwduf" + + "n1S1o\""), + + publish.newTXTChange(ChangeAction.UPSERT, "n", + AwsClient.rootTTL, + "\"tree-root-v1:CjoKGkZEWE4zU042N05BNURLQTRKMkdPSzdCVlFJEhpGRFhOM1NONjdOQTVES0E0SjJHT" + + "0s3QlZRSRgJElc5aDU4d1cyajUzdlBMeHNBSGN1cDMtV0ZEM2lvZUk4SkJrZkdYSk93dmI0R0lHR01" + + "pQVAxRkJVVGc4bHlORERleXJkck9uSDdSbUNUUnJRVGxqUm9UaHM\""), + + publish.newTXTChange(ChangeAction.DELETE, "2kfjogvxdqtxxugbh7gs7naaai.n", + 3333, + "nodes:-HW4QO1ml1DdXLeZLsUxewnthhUy8eROqkDyoMTyavfks9JlYQIlMFEUoM78PovJDPQrAkrb3LRJ-", + "vtrymDguKCOIAWAgmlkgnY0iXNlY3AyNTZrMaEDffaGfJzgGhUif1JqFruZlYmA31HzathLSWxfbq_QoQ4"), + publish.newTXTChange(ChangeAction.DELETE, "fdxn3sn67na5dka4j2gok7bvqi.n", + AwsClient.treeNodeTTL, + "tree-branch:") + }; + + Assert.assertEquals(wantChanges.length, changes.size()); + for (int i = 0; i < changes.size(); i++) { + Assert.assertTrue(wantChanges[i].equalsBySdkFields(changes.get(i))); + Assert.assertTrue(AwsClient.isSameChange(wantChanges[i], changes.get(i))); + } + } + + @Test + public void testPublish() throws UnknownHostException { + + DnsNode[] nodes = TreeTest.sampleNode(); + List nodeList = Arrays.asList(nodes); + List enrList = Tree.merge(nodeList, new PublishConfig().getMaxMergeSize()); + + String[] links = new String[] { + "tree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@example1.org", + "tree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@example2.org"}; + List linkList = Arrays.asList(links); + + Tree tree = new Tree(); + try { + tree.makeTree(1, enrList, linkList, AlgorithmTest.privateKey); + } catch (DnsException e) { + Assert.fail(); + } + + // //warning: replace your key in the following section, or this test will fail + // AwsClient awsClient; + // try { + // awsClient = new AwsClient("replace your access key", + // "replace your access key secret", + // "replace your host zone id", + // Region.US_EAST_1); + // } catch (DnsException e) { + // Assert.fail(); + // return; + // } + // String domain = "replace with your domain"; + // try { + // awsClient.deploy(domain, tree); + // } catch (Exception e) { + // Assert.fail(); + // return; + // } + // + // BigInteger publicKeyInt = + // Algorithm.generateKeyPair(AlgorithmTest.privateKey).getPublicKey(); + // String puKeyCompress = Algorithm.compressPubKey(publicKeyInt); + // String base32Pubkey = Algorithm.encode32(ByteArray.fromHexString(puKeyCompress)); + // Client client = new Client(); + // + // Tree route53Tree = new Tree(); + // try { + // client.syncTree(Entry.linkPrefix + base32Pubkey + "@" + domain, null, + // route53Tree); + // } catch (Exception e) { + // Assert.fail(); + // return; + // } + // Assert.assertEquals(links.length, route53Tree.getLinksEntry().size()); + // Assert.assertEquals(nodes.length, route53Tree.getDnsNodes().size()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/DnsManagerTest.java b/p2p/src/test/java/org/tron/p2p/dns/DnsManagerTest.java new file mode 100644 index 00000000000..41bcd538f7d --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/DnsManagerTest.java @@ -0,0 +1,143 @@ +package org.tron.p2p.dns; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.dns.sync.Client; +import org.tron.p2p.dns.tree.Tree; + +/** + * Covers DnsManager.getDnsNodes, which turns synced DNS trees into the connectable + * node list. Two filters matter: a node with no usable address for this host must be + * dropped, and this host's own addresses must not be handed back as peers to dial. + */ +public class DnsManagerTest { + + private Client syncClient; + private Object priorSyncClient; + private Object priorLocalIpSet; + + private static Object getStatic(String name) throws Exception { + Field field = DnsManager.class.getDeclaredField(name); + field.setAccessible(true); + return field.get(null); + } + + private static void setStatic(String name, Object value) throws Exception { + Field field = DnsManager.class.getDeclaredField(name); + field.setAccessible(true); + field.set(null, value); + } + + @Before + public void setUp() throws Exception { + // getPreferInetSocketAddress() consults the local config to decide whether v4 or + // v6 is usable, so it must be initialised before any node is evaluated + Parameter.p2pConfig = new P2pConfig(); + Parameter.p2pConfig.setIp("1.1.1.1"); + Parameter.p2pConfig.setIpv6(null); + + // DnsManager's collaborators are process-wide statics and framework's test task + // reuses a JVM across up to 100 classes (forkEvery = 100), so they are restored in + // tearDown rather than left pointing at a mock from a finished test class + priorSyncClient = getStatic("syncClient"); + priorLocalIpSet = getStatic("localIpSet"); + + syncClient = mock(Client.class); + setStatic("syncClient", syncClient); + setStatic("localIpSet", new HashSet()); + } + + @After + public void tearDown() throws Exception { + setStatic("syncClient", priorSyncClient); + setStatic("localIpSet", priorLocalIpSet); + } + + private void serveTree(List nodes) { + Tree tree = mock(Tree.class); + when(tree.getDnsNodes()).thenReturn(nodes); + Map trees = new HashMap<>(); + trees.put("tree://example.org", tree); + when(syncClient.getTrees()).thenReturn(trees); + } + + @Test + public void returnsEmptyWhenNoTreesAreSynced() { + when(syncClient.getTrees()).thenReturn(new HashMap<>()); + Assert.assertTrue(DnsManager.getDnsNodes().isEmpty()); + } + + @Test + public void returnsConnectableV4Nodes() throws Exception { + List nodes = new ArrayList<>(); + nodes.add(new DnsNode(null, "2.2.2.2", null, 18888)); + nodes.add(new DnsNode(null, "3.3.3.3", null, 18888)); + serveTree(nodes); + + List result = DnsManager.getDnsNodes(); + Assert.assertEquals(2, result.size()); + } + + @Test + public void dropsNodesWithNoAddressUsableByThisHost() throws Exception { + // this host has no IPv6 configured, so a v6-only peer is not connectable + List nodes = new ArrayList<>(); + nodes.add(new DnsNode(null, "2.2.2.2", null, 18888)); + nodes.add(new DnsNode(null, null, "2001:db8::1", 18888)); + serveTree(nodes); + + List result = DnsManager.getDnsNodes(); + Assert.assertEquals(1, result.size()); + Assert.assertEquals("2.2.2.2", result.get(0).getHostV4()); + } + + @Test + public void dropsThisHostsOwnAddresses() throws Exception { + Set local = new HashSet<>(); + local.add("2.2.2.2"); + setStatic("localIpSet", local); + + List nodes = new ArrayList<>(); + nodes.add(new DnsNode(null, "2.2.2.2", null, 18888)); + nodes.add(new DnsNode(null, "3.3.3.3", null, 18888)); + serveTree(nodes); + + List result = DnsManager.getDnsNodes(); + Assert.assertEquals(1, result.size()); + Assert.assertEquals("3.3.3.3", result.get(0).getHostV4()); + } + + @Test + public void deduplicatesAcrossTrees() throws Exception { + // the same peer advertised by two trees must be dialled once + List first = new ArrayList<>(); + first.add(new DnsNode(null, "2.2.2.2", null, 18888)); + List second = new ArrayList<>(); + second.add(new DnsNode(null, "2.2.2.2", null, 18888)); + + Tree treeA = mock(Tree.class); + when(treeA.getDnsNodes()).thenReturn(first); + Tree treeB = mock(Tree.class); + when(treeB.getDnsNodes()).thenReturn(second); + Map trees = new HashMap<>(); + trees.put("tree://a.example.org", treeA); + trees.put("tree://b.example.org", treeB); + when(syncClient.getTrees()).thenReturn(trees); + + Assert.assertEquals(1, DnsManager.getDnsNodes().size()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/DnsNodeTest.java b/p2p/src/test/java/org/tron/p2p/dns/DnsNodeTest.java new file mode 100644 index 00000000000..549271b4187 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/DnsNodeTest.java @@ -0,0 +1,52 @@ +package org.tron.p2p.dns; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + +public class DnsNodeTest { + + @Test + public void testCompressDnsNode() throws UnknownHostException, InvalidProtocolBufferException { + DnsNode[] nodes = new DnsNode[] { + new DnsNode(null, "192.168.0.1", null, 10000), + }; + List nodeList = Arrays.asList(nodes); + String enrContent = DnsNode.compress(nodeList); + + List dnsNodes = DnsNode.decompress(enrContent); + Assert.assertEquals(1, dnsNodes.size()); + Assert.assertTrue(nodes[0].equals(dnsNodes.get(0))); + } + + @Test + public void testSortDnsNode() throws UnknownHostException { + DnsNode[] nodes = new DnsNode[] { + new DnsNode(null, "192.168.0.1", null, 10000), + new DnsNode(null, "192.168.0.2", null, 10000), + new DnsNode(null, "192.168.0.3", null, 10000), + new DnsNode(null, "192.168.0.4", null, 10000), + new DnsNode(null, "192.168.0.5", null, 10000), + new DnsNode(null, "192.168.0.6", null, 10001), + new DnsNode(null, "192.168.0.6", null, 10002), + new DnsNode(null, "192.168.0.6", null, 10003), + new DnsNode(null, "192.168.0.6", null, 10004), + new DnsNode(null, "192.168.0.6", null, 10005), + new DnsNode(null, "192.168.0.10", "fe80::0001", 10005), + new DnsNode(null, "192.168.0.10", "fe80::0002", 10005), + new DnsNode(null, null, "fe80::0001", 10000), + new DnsNode(null, null, "fe80::0002", 10000), + new DnsNode(null, null, "fe80::0002", 10001), + }; + List nodeList = Arrays.asList(nodes); + Collections.shuffle(nodeList); //random order + Collections.sort(nodeList); + for (int i = 0; i < nodeList.size(); i++) { + Assert.assertTrue(nodes[i].equals(nodeList.get(i))); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/LinkCacheTest.java b/p2p/src/test/java/org/tron/p2p/dns/LinkCacheTest.java new file mode 100644 index 00000000000..2893e1f8a9d --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/LinkCacheTest.java @@ -0,0 +1,35 @@ +package org.tron.p2p.dns; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.dns.sync.LinkCache; + +public class LinkCacheTest { + + @Test + public void testLinkCache() { + LinkCache lc = new LinkCache(); + + lc.addLink("1", "2"); + Assert.assertTrue(lc.isChanged()); + + lc.setChanged(false); + lc.addLink("1", "2"); + Assert.assertFalse(lc.isChanged()); + + lc.addLink("2", "3"); + lc.addLink("3", "1"); + lc.addLink("2", "4"); + + for (String key : lc.getBackrefs().keySet()) { + System.out.println(key + ":" + StringUtils.join(lc.getBackrefs().get(key), ",")); + } + Assert.assertTrue(lc.isContainInOtherLink("3")); + Assert.assertFalse(lc.isContainInOtherLink("6")); + + lc.resetLinks("1", null); + Assert.assertTrue(lc.isChanged()); + Assert.assertEquals(0, lc.getBackrefs().size()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/RandomTest.java b/p2p/src/test/java/org/tron/p2p/dns/RandomTest.java new file mode 100644 index 00000000000..9655bcdf6e3 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/RandomTest.java @@ -0,0 +1,36 @@ +package org.tron.p2p.dns; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.dns.sync.Client; +import org.tron.p2p.dns.sync.RandomIterator; + +public class RandomTest { + + @Test + public void testRandomIterator() { + Parameter.p2pConfig = new P2pConfig(); + List treeUrls = new ArrayList<>(); + treeUrls.add( + "tree://AKMQMNAJJBL73LXWPXDI4I5ZWWIZ4AWO34DWQ636QOBBXNFXH3LQS@nile.trondisco.net"); + //treeUrls.add( + // "tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@shasta.nftderby1.net"); + Parameter.p2pConfig.setTreeUrls(treeUrls); + + Client syncClient = new Client(); + + RandomIterator randomIterator = syncClient.newIterator(); + int count = 0; + while (count < 20) { + DnsNode dnsNode = randomIterator.next(); + Assert.assertNotNull(dnsNode); + Assert.assertNull(dnsNode.getId()); + count += 1; + System.out.println("get Node success:" + dnsNode.format()); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/SyncTest.java b/p2p/src/test/java/org/tron/p2p/dns/SyncTest.java new file mode 100644 index 00000000000..6099dc2edf9 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/SyncTest.java @@ -0,0 +1,33 @@ +package org.tron.p2p.dns; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.dns.sync.Client; +import org.tron.p2p.dns.sync.ClientTree; +import org.tron.p2p.dns.tree.Tree; + +public class SyncTest { + + @Test + public void testSync() { + Parameter.p2pConfig = new P2pConfig(); + List treeUrls = new ArrayList<>(); + treeUrls.add( + "tree://AKMQMNAJJBL73LXWPXDI4I5ZWWIZ4AWO34DWQ636QOBBXNFXH3LQS@nile.trondisco.net"); + Parameter.p2pConfig.setTreeUrls(treeUrls); + + Client syncClient = new Client(); + + ClientTree clientTree = new ClientTree(syncClient); + Tree tree = new Tree(); + try { + syncClient.syncTree(Parameter.p2pConfig.getTreeUrls().get(0), clientTree, tree); + } catch (Exception e) { + Assert.fail(); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/TreeTest.java b/p2p/src/test/java/org/tron/p2p/dns/TreeTest.java new file mode 100644 index 00000000000..6e3ae6c6f3d --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/TreeTest.java @@ -0,0 +1,248 @@ +package org.tron.p2p.dns; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.dns.tree.Algorithm; +import org.tron.p2p.dns.tree.Entry; +import org.tron.p2p.dns.tree.Tree; +import org.tron.p2p.dns.update.PublishConfig; +import org.tron.p2p.exception.DnsException; + +public class TreeTest { + + public static DnsNode[] sampleNode() throws UnknownHostException { + return new DnsNode[] { + new DnsNode(null, "192.168.0.1", null, 10000), + new DnsNode(null, "192.168.0.2", null, 10000), + new DnsNode(null, "192.168.0.3", null, 10000), + new DnsNode(null, "192.168.0.4", null, 10000), + new DnsNode(null, "192.168.0.5", null, 10000), + new DnsNode(null, "192.168.0.6", null, 10001), + new DnsNode(null, "192.168.0.6", null, 10002), + new DnsNode(null, "192.168.0.6", null, 10003), + new DnsNode(null, "192.168.0.6", null, 10004), + new DnsNode(null, "192.168.0.6", null, 10005), + new DnsNode(null, "192.168.0.10", "fe80::0001", 10005), + new DnsNode(null, "192.168.0.10", "fe80::0002", 10005), + new DnsNode(null, null, "fe80::0001", 10000), + new DnsNode(null, null, "fe80::0002", 10000), + new DnsNode(null, null, "fe80::0003", 10001), + new DnsNode(null, null, "fe80::0004", 10001), + }; + } + + @Test + public void testMerge() throws UnknownHostException { + DnsNode[] nodes = sampleNode(); + List nodeList = Arrays.asList(nodes); + + int maxMergeSize = new PublishConfig().getMaxMergeSize(); + List enrs = Tree.merge(nodeList, maxMergeSize); + int total = 0; + for (int i = 0; i < enrs.size(); i++) { + List subList = null; + try { + subList = DnsNode.decompress(enrs.get(i).substring(Entry.nodesPrefix.length())); + } catch (InvalidProtocolBufferException e) { + Assert.fail(); + } + Assert.assertTrue(subList.size() <= maxMergeSize); + total += subList.size(); + } + Assert.assertEquals(nodeList.size(), total); + } + + @Test + public void testTreeBuild() throws UnknownHostException { + int seq = 0; + + DnsNode[] dnsNodes = new DnsNode[] { + new DnsNode(null, "192.168.0.1", null, 10000), + new DnsNode(null, "192.168.0.2", null, 10000), + new DnsNode(null, "192.168.0.3", null, 10000), + new DnsNode(null, "192.168.0.4", null, 10000), + new DnsNode(null, "192.168.0.5", null, 10000), + new DnsNode(null, "192.168.0.6", null, 10000), + new DnsNode(null, "192.168.0.7", null, 10000), + new DnsNode(null, "192.168.0.8", null, 10000), + new DnsNode(null, "192.168.0.9", null, 10000), + new DnsNode(null, "192.168.0.10", null, 10000), + + new DnsNode(null, "192.168.0.11", null, 10000), + new DnsNode(null, "192.168.0.12", null, 10000), + new DnsNode(null, "192.168.0.13", null, 10000), + new DnsNode(null, "192.168.0.14", null, 10000), + new DnsNode(null, "192.168.0.15", null, 10000), + new DnsNode(null, "192.168.0.16", null, 10000), + new DnsNode(null, "192.168.0.17", null, 10000), + new DnsNode(null, "192.168.0.18", null, 10000), + new DnsNode(null, "192.168.0.19", null, 10000), + new DnsNode(null, "192.168.0.20", null, 10000), + + new DnsNode(null, "192.168.0.21", null, 10000), + new DnsNode(null, "192.168.0.22", null, 10000), + new DnsNode(null, "192.168.0.23", null, 10000), + new DnsNode(null, "192.168.0.24", null, 10000), + new DnsNode(null, "192.168.0.25", null, 10000), + new DnsNode(null, "192.168.0.26", null, 10000), + new DnsNode(null, "192.168.0.27", null, 10000), + new DnsNode(null, "192.168.0.28", null, 10000), + new DnsNode(null, "192.168.0.29", null, 10000), + new DnsNode(null, "192.168.0.30", null, 10000), + + new DnsNode(null, "192.168.0.31", null, 10000), + new DnsNode(null, "192.168.0.32", null, 10000), + new DnsNode(null, "192.168.0.33", null, 10000), + new DnsNode(null, "192.168.0.34", null, 10000), + new DnsNode(null, "192.168.0.35", null, 10000), + new DnsNode(null, "192.168.0.36", null, 10000), + new DnsNode(null, "192.168.0.37", null, 10000), + new DnsNode(null, "192.168.0.38", null, 10000), + new DnsNode(null, "192.168.0.39", null, 10000), + new DnsNode(null, "192.168.0.40", null, 10000), + }; + + String[] enrs = new String[dnsNodes.length]; + for (int i = 0; i < dnsNodes.length; i++) { + DnsNode dnsNode = dnsNodes[i]; + List nodeList = new ArrayList<>(); + nodeList.add(dnsNode); + enrs[i] = Entry.nodesPrefix + DnsNode.compress(nodeList); + } + + String[] links = new String[] {}; + + String linkBranch0 = "tree-branch:"; + String enrBranch1 = "tree-branch:OX22LN2ZUGOPGIPGBUQH35KZU4,XTGCXXQHPK3VUZPQHC6CGJDR3Q,BQLJLB6" + + "P5CRXHI37BRVWBWWACY,X4FURUK4SHXW3GVE6XBO3DFD5Y,SIUYMSVBYYXCE6HVW5TSGOFKVQ,2RKY3FUYIQBV4" + + "TFIDU7S42EIEU,KSEEGRTUGR4GCCBQ4TYHAWDKME,YGWDS6F6KLTFCC7T3AMAJHXI2A,K4HMVDEHRKOGOFQZXBJ" + + "2PSVIMM,NLLRMPWOTS6SP4D7YLCQA42IQQ,BBDLEDOZYAX5CWM6GNAALRVUXY,7NMT4ZISY5F4U6B6CQML2C526" + + "E,NVDRYMFHIERJEVGW5TE7QEAS2A"; + String enrBranch2 = "tree-branch:5ELKMY4HVAV5CBY6KDMXWOFSN4,7PHYT72EXSZJ6MT2IQ7VGUFQHI,AM6BJFC" + + "ERRNKBG4A5X3MORBDZU,2WOYKPVTNYAY3KVDTDY4CEVOJM,PW5BHSJMPEHVJKRF5QTRXQB4LU,IS4YMOJGD4XPO" + + "DBAMHZOUTIVMI,NSEE5WE57FWG2EERXI5TBBD32E,GOLZDJTTQ7V2MO2BG45O3Q22XI,4VL7USGBWKW576WM4TX" + + "7XIXS4A,GZQSPHDZYS7FXURGOQU3RIDUK4,T7L645CJJKCQVQMUADDO44EGOM,ATPMZZZB4RGYKC6K7QDFC22WI" + + "E,57KNNYA4WOKVZAODRCFYK64MBA"; + String enrBranch3 = "tree-branch:BJF5S37KVATG2SYHO6M7APDCNU,OUB3BDKUZQWXXFX5OSF5JCB6BA,6JZEHDW" + + "M6WWQYIEYVZN5QVMUXA,LXNNOBVTTZBPD3N5VTOCPVG7JE,LMWLKDCBT2U3CGSHKR2PYJNV5I,K2SSCP4ZIF7TQ" + + "I4MRVLELFAQQE,MKR7II3GYETKN7MSCUQOF6MBQ4,FBJ5VFCV37SGUOEYA2SPGO3TLA,6SHSDL7PJCJAER3OS53" + + "NYPNDFI,KYU2OQJBU6AU3KJFCUSLOJWKVE,3N6XKDWY3WTBOSBS22YPUAHCFQ,IPEWOISXUGOL7ORZIOXBD24SP" + + "I,PCGDGGVEQQQFL4U2FYRXVHVMUM"; + String enrBranch4 = "tree-branch:WHCXLEQB3467BFATRY5SMIV62M,LAHEXJDXOPZSS2TDVXTJACCB6Q,QR4HMFZ" + + "U3STBJEXOZIXPDRQTGM,JZUKVXBOLBPXCELWIE5G6E6UUU"; + + String[] branches = new String[] {linkBranch0, enrBranch1, enrBranch2, enrBranch3, enrBranch4}; + + List branchList = Arrays.asList(branches); + List enrList = Arrays.asList(enrs); + List linkList = Arrays.asList(links); + + Tree tree = new Tree(); + try { + tree.makeTree(seq, enrList, linkList, null); + } catch (DnsException e) { + Assert.fail(); + } + + /* + b r a n c h 4 + / / \ \ + / / \ \ + / / \ \ + branch1 branch2 branch3 \ + / \ / \ / \ \ + node:-01 ~ node:-13 node:-14 ~ node:-26 node:-27 ~ node:-39 node:-40 + */ + + Assert.assertEquals(branchList.size() + enrList.size() + linkList.size(), + tree.getEntries().size()); + Assert.assertEquals(branchList.size(), tree.getBranchesEntry().size()); + Assert.assertEquals(enrList.size(), tree.getNodesEntry().size()); + Assert.assertEquals(linkList.size(), tree.getLinksEntry().size()); + + for (String branch : tree.getBranchesEntry()) { + Assert.assertTrue(branchList.contains(branch)); + } + for (String nodeEntry : tree.getNodesEntry()) { + Assert.assertTrue(enrList.contains(nodeEntry)); + } + for (String link : tree.getLinksEntry()) { + Assert.assertTrue(linkList.contains(link)); + } + + Assert.assertEquals(Algorithm.encode32AndTruncate(enrBranch4), tree.getRootEntry().getERoot()); + Assert.assertEquals(Algorithm.encode32AndTruncate(linkBranch0), tree.getRootEntry().getLRoot()); + Assert.assertEquals(seq, tree.getSeq()); + } + + @Test + public void testGroupAndMerge() throws UnknownHostException { + Random random = new Random(); + //simulate some nodes + int ipCount = 2000; + int maxMergeSize = 5; + List dnsNodes = new ArrayList<>(); + Set ipSet = new HashSet<>(); + int i = 0; + while (i < ipCount) { + i += 1; + String ip = String.format("%d.%d.%d.%d", random.nextInt(256), random.nextInt(256), + random.nextInt(256), random.nextInt(256)); + if (ipSet.contains(ip)) { + continue; + } + ipSet.add(ip); + dnsNodes.add(new DnsNode(null, ip, null, 10000)); + } + Set enrSet1 = new HashSet<>(Tree.merge(dnsNodes, maxMergeSize)); + System.out.println("srcSize:" + enrSet1.size()); + + // delete some node + int deleteCount = 100; + i = 0; + while (i < deleteCount) { + i += 1; + int deleteIndex = random.nextInt(dnsNodes.size()); + dnsNodes.remove(deleteIndex); + } + + // add some node + int addCount = 100; + i = 0; + while (i < addCount) { + i += 1; + String ip = String.format("%d.%d.%d.%d", random.nextInt(256), random.nextInt(256), + random.nextInt(256), random.nextInt(256)); + if (ipSet.contains(ip)) { + continue; + } + ipSet.add(ip); + dnsNodes.add(new DnsNode(null, ip, null, 10000)); + } + Set enrSet2 = new HashSet<>(Tree.merge(dnsNodes, maxMergeSize)); + + // calculate changes + Set enrSet3 = new HashSet<>(enrSet2); + enrSet3.removeAll(enrSet1); // enrSet2 - enrSet1 + System.out.println("addSize:" + enrSet3.size()); + Assert.assertTrue(enrSet3.size() < enrSet1.size()); + + Set enrSet4 = new HashSet<>(enrSet1); + enrSet4.removeAll(enrSet2); //enrSet1 - enrSet2 + System.out.println("deleteSize:" + enrSet4.size()); + Assert.assertTrue(enrSet4.size() < enrSet1.size()); + + Set enrSet5 = new HashSet<>(enrSet1); + enrSet5.retainAll(enrSet2); // enrSet1 && enrSet2 + System.out.println("intersectionSize:" + enrSet5.size()); + Assert.assertTrue(enrSet5.size() < enrSet1.size()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/lookup/LookUpTxtTest.java b/p2p/src/test/java/org/tron/p2p/dns/lookup/LookUpTxtTest.java new file mode 100644 index 00000000000..f02244d4ada --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/lookup/LookUpTxtTest.java @@ -0,0 +1,88 @@ +package org.tron.p2p.dns.lookup; + +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.util.Arrays; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.xbill.DNS.DClass; +import org.xbill.DNS.Name; +import org.xbill.DNS.TXTRecord; +import org.xbill.DNS.TextParseException; + +public class LookUpTxtTest { + + @Test + public void testJoinTXTRecord_singleString() throws TextParseException { + Name name = Name.fromString("test.example.com."); + TXTRecord record = new TXTRecord(name, DClass.IN, 300, "hello"); + Assert.assertEquals("hello", LookUpTxt.joinTXTRecord(record)); + } + + @Test + public void testJoinTXTRecord_multipleStrings() throws TextParseException { + Name name = Name.fromString("test.example.com."); + TXTRecord record = new TXTRecord(name, DClass.IN, 300, + Arrays.asList("enrtree-root:v1 ", "e=ABCDE ", "l=FGHIJ seq=1 sig=XYZ")); + // joinTXTRecord trims each string before concatenating, so trailing spaces are removed + Assert.assertEquals("enrtree-root:v1e=ABCDEl=FGHIJ seq=1 sig=XYZ", + LookUpTxt.joinTXTRecord(record)); + } + + // ------------------------------------------------------------------------- + // lookUpIp tests + // ------------------------------------------------------------------------- + + /** + * "localhost" is always present in /etc/hosts on every OS, so InetAddress.getByName resolves it + * locally without issuing any DNS query — this validates the /etc/hosts fast path. + */ + @Test + @Ignore("might fail due to no netowrk") + public void testLookUpIp_localhost_ipv4_resolvesViaHosts() { + InetAddress address = LookUpTxt.lookUpIp("localhost", true); + Assert.assertNotNull("localhost must resolve via /etc/hosts", address); + Assert.assertTrue("Expected IPv4 loopback", address instanceof Inet4Address); + Assert.assertTrue("Expected loopback address", address.isLoopbackAddress()); + } + + @Test + @Ignore("might fail due to no netowrk") + public void testLookUpIp_localhost_ipv6_resolvesViaHosts() { + InetAddress address = LookUpTxt.lookUpIp("localhost", false); + Assert.assertNotNull("localhost must resolve via /etc/hosts", address); + Assert.assertTrue("Expected IPv6 loopback", address instanceof Inet6Address); + Assert.assertTrue("Expected loopback address", address.isLoopbackAddress()); + } + + /** + * example.com is a stable IANA-reserved domain that always has an A record. + * This validates the normal DNS resolution path (Step 1 via OS resolver). + */ + @Test + @Ignore("might fail due to no netowrk") + public void testLookUpIp_wellKnownDomain_ipv4_returnsNonNull() { + InetAddress address = LookUpTxt.lookUpIp("example.com", true); + Assert.assertNotNull("example.com should resolve to an IPv4 address", address); + Assert.assertTrue("Expected Inet4Address", address instanceof Inet4Address); + } + + /** + * The ".invalid" TLD is RFC 2606-reserved and guaranteed never to resolve. + * All three resolution steps (OS, default DNS, public DNS) should fail, returning null. + */ + @Test + public void testLookUpIp_nonexistentDomain_returnsNull() { + int saved = LookUpTxt.maxRetryTimes; + LookUpTxt.maxRetryTimes = 1; + try { + InetAddress address = + LookUpTxt.lookUpIp("this.domain.absolutely.does.not.exist.invalid", true); + Assert.assertNull("Non-existent domain should return null", address); + } finally { + LookUpTxt.maxRetryTimes = saved; + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/tree/TreeSignAndTxtTest.java b/p2p/src/test/java/org/tron/p2p/dns/tree/TreeSignAndTxtTest.java new file mode 100644 index 00000000000..cf4ea3059ee --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/tree/TreeSignAndTxtTest.java @@ -0,0 +1,146 @@ +package org.tron.p2p.dns.tree; + +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.dns.DnsNode; +import org.tron.p2p.dns.update.AliClient; + +/** + * The publish side of Tree: signing the root, and rendering the tree as the TXT + * record map that goes to the DNS provider. Both Aliyun (bare "@" root) and + * Route53 (fully qualified names) shapes are covered. + */ +public class TreeSignAndTxtTest { + + private static final String PRIVATE_KEY = + "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291"; + private static final String DOMAIN = "nodes.example.org"; + + private static List enrsFor(String... ips) throws UnknownHostException { + List enrs = new ArrayList<>(); + for (String ip : ips) { + enrs.add(Entry.nodesPrefix + + DnsNode.compress(Collections.singletonList(new DnsNode(null, ip, null, 10000)))); + } + return enrs; + } + + private static Tree signedTree(int seq) throws Exception { + Tree tree = new Tree(); + tree.makeTree(seq, enrsFor("192.168.0.1", "192.168.0.2", "192.168.0.3"), + new ArrayList(), PRIVATE_KEY); + return tree; + } + + @Test + public void makeTreeSignsTheRootAndExposesThePublicKey() throws Exception { + Tree tree = signedTree(7); + + Assert.assertEquals(7, tree.getSeq()); + Assert.assertNotNull(tree.getBase32PublicKey()); + Assert.assertFalse(tree.getBase32PublicKey().isEmpty()); + Assert.assertFalse(tree.getNodesEntry().isEmpty()); + Assert.assertTrue(tree.getLinksEntry().isEmpty()); + } + + @Test + public void seqIsMutableAndResigningSucceeds() throws Exception { + Tree tree = signedTree(1); + tree.setSeq(42); + Assert.assertEquals(42, tree.getSeq()); + // deploy() bumps the sequence and re-signs; that must not throw. + tree.sign(); + Assert.assertEquals(42, tree.getSeq()); + } + + @Test + public void toTxtQualifiesEveryHashWithTheRootDomain() throws Exception { + Tree tree = signedTree(1); + Map records = tree.toTXT(DOMAIN); + + Assert.assertTrue("the root record is keyed by the domain itself", + records.containsKey(DOMAIN)); + Assert.assertTrue(records.get(DOMAIN).startsWith(Entry.rootPrefix)); + + int subdomains = 0; + for (Map.Entry record : records.entrySet()) { + if (record.getKey().equals(DOMAIN)) { + continue; + } + subdomains++; + Assert.assertTrue(record.getKey() + " should sit under the domain", + record.getKey().endsWith("." + DOMAIN)); + Assert.assertEquals("keys are lower-cased", + record.getKey().toLowerCase(java.util.Locale.ROOT), record.getKey()); + } + Assert.assertTrue(subdomains > 0); + } + + @Test + public void toTxtWithoutARootDomainUsesTheAliyunRootSymbol() throws Exception { + Tree tree = signedTree(1); + Map records = tree.toTXT(null); + + Assert.assertTrue(records.containsKey(AliClient.aliyunRoot)); + Assert.assertTrue(records.get(AliClient.aliyunRoot).startsWith(Entry.rootPrefix)); + for (String key : records.keySet()) { + Assert.assertFalse("bare hashes only, no domain suffix", key.endsWith("." + DOMAIN)); + } + } + + @Test + public void entryAccessorsAgreeWithEachOther() throws Exception { + Tree tree = signedTree(1); + + Assert.assertEquals(tree.getNodesEntry().size(), tree.getNodesMap().size()); + Assert.assertEquals(tree.getLinksEntry().size(), tree.getLinksMap().size()); + Assert.assertFalse(tree.getDnsNodes().isEmpty()); + // Every entry is either a node set, a link, or a branch. + Assert.assertEquals(tree.getEntries().size(), + tree.getNodesEntry().size() + tree.getLinksEntry().size() + + tree.getBranchesEntry().size()); + } + + @Test + public void mergeGroupsByNetworkAndRespectsTheBatchSize() throws Exception { + List nodes = Arrays.asList( + new DnsNode(null, "192.168.0.1", null, 10000), + new DnsNode(null, "192.168.0.2", null, 10000), + new DnsNode(null, "10.0.0.1", null, 10000)); + + // Nodes in different /8 networks are never merged into one entry. + List merged = Tree.merge(new ArrayList<>(nodes), 10); + Assert.assertEquals(2, merged.size()); + for (String entry : merged) { + Assert.assertTrue(entry.startsWith(Entry.nodesPrefix)); + } + + // A batch size of one puts every node in its own entry. + Assert.assertEquals(3, Tree.merge(new ArrayList<>(nodes), 1).size()); + } + + @Test + public void mergeOfNothingProducesNothing() { + Assert.assertTrue(Tree.merge(new ArrayList(), 10).isEmpty()); + } + + @Test + public void signingWithoutAPrivateKeyIsSilentlySkipped() throws Exception { + Tree tree = new Tree(); + tree.makeTree(1, enrsFor("192.168.0.1"), new ArrayList(), null); + tree.sign(); + + // sign() returns early on an empty key rather than refusing, so the tree is + // left unsigned and with no public key. The publisher does not check either, + // which is how an unsigned "tree://null@..." can reach DNS. Pinned here as + // current behaviour, not as an endorsement. + Assert.assertNull(tree.getBase32PublicKey()); + Assert.assertTrue(tree.toTXT(DOMAIN).get(DOMAIN).startsWith(Entry.rootPrefix)); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/update/AliClientDeployTest.java b/p2p/src/test/java/org/tron/p2p/dns/update/AliClientDeployTest.java new file mode 100644 index 00000000000..db7f3229db8 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/update/AliClientDeployTest.java @@ -0,0 +1,192 @@ +package org.tron.p2p.dns.update; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.aliyun.alidns20150109.Client; +import com.aliyun.alidns20150109.models.AddDomainRecordRequest; +import com.aliyun.alidns20150109.models.AddDomainRecordResponse; +import com.aliyun.alidns20150109.models.AddDomainRecordResponseBody; +import com.aliyun.alidns20150109.models.DeleteDomainRecordRequest; +import com.aliyun.alidns20150109.models.DeleteDomainRecordResponse; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsRequest; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsResponse; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsResponseBody; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecords; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecordsRecord; +import com.aliyun.alidns20150109.models.UpdateDomainRecordRequest; +import com.aliyun.alidns20150109.models.UpdateDomainRecordResponse; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.dns.DnsNode; +import org.tron.p2p.dns.tree.Entry; +import org.tron.p2p.dns.tree.Tree; +import org.tron.p2p.exception.DnsException; + +/** + * AliClient.deploy end to end with the Aliyun SDK mocked: the changeThreshold + * decision, and the add / update / delete selection inside submitChanges. + */ +public class AliClientDeployTest { + + private static final String DOMAIN = "nodes.example.org"; + private static final int SUCCESS = 200; + private static final String PRIVATE_KEY = + "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291"; + + private Client sdk; + private AliClient client; + + @Before + public void setUp() throws Exception { + sdk = mock(Client.class); + client = new AliClient("alidns.aliyuncs.com", "key-id", "key-secret", 0.1); + Field field = AliClient.class.getDeclaredField("aliDnsClient"); + field.setAccessible(true); + field.set(client, sdk); + + when(sdk.addDomainRecord(any(AddDomainRecordRequest.class))) + .thenReturn((AddDomainRecordResponse) new AddDomainRecordResponse() + .setStatusCode(SUCCESS).setBody(new AddDomainRecordResponseBody().setRecordId("r1"))); + when(sdk.updateDomainRecord(any(UpdateDomainRecordRequest.class))) + .thenReturn((UpdateDomainRecordResponse) new UpdateDomainRecordResponse() + .setStatusCode(SUCCESS)); + when(sdk.deleteDomainRecord(any(DeleteDomainRecordRequest.class))) + .thenReturn((DeleteDomainRecordResponse) new DeleteDomainRecordResponse() + .setStatusCode(SUCCESS)); + } + + private static DescribeDomainRecordsResponse records( + DescribeDomainRecordsResponseBodyDomainRecordsRecord... items) { + DescribeDomainRecordsResponseBody body = new DescribeDomainRecordsResponseBody() + .setTotalCount((long) items.length) + .setDomainRecords(new DescribeDomainRecordsResponseBodyDomainRecords() + .setRecord(new ArrayList<>(Arrays.asList(items)))); + return (DescribeDomainRecordsResponse) new DescribeDomainRecordsResponse() + .setStatusCode(SUCCESS).setBody(body); + } + + private static Tree signedTree(String... ips) throws Exception { + List enrs = new ArrayList<>(); + for (String ip : ips) { + enrs.add(Entry.nodesPrefix + + DnsNode.compress(Collections.singletonList(new DnsNode(null, ip, null, 10000)))); + } + Tree tree = new Tree(); + tree.makeTree(1, enrs, new ArrayList(), PRIVATE_KEY); + return tree; + } + + @SuppressWarnings("unchecked") + private void setServerNodes(Set nodes) throws Exception { + Field field = AliClient.class.getDeclaredField("serverNodes"); + field.setAccessible(true); + field.set(client, nodes); + } + + @Test + public void deployOnAnEmptyZoneAddsEveryRecord() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(records()); + + client.deploy(DOMAIN, signedTree("192.168.0.1", "192.168.0.2")); + + // Nothing existed, so every TXT record is an add and nothing is updated. + verify(sdk, atLeastOnce()).addDomainRecord(any(AddDomainRecordRequest.class)); + verify(sdk, never()).updateDomainRecord(any(UpdateDomainRecordRequest.class)); + } + + @Test + public void deployBelowTheChangeThresholdSkipsEverything() throws Exception { + // deploy() re-reads serverNodes from DNS, so the "already published" set has + // to come back through the mocked describeDomainRecords rather than being + // planted on the client. + String[] ips = new String[40]; + for (int i = 0; i < ips.length; i++) { + ips[i] = "10.0.0." + (i + 1); + } + Tree tree = signedTree(ips); + + List published = new ArrayList<>(); + int index = 0; + for (String entry : tree.getNodesEntry()) { + published.add(new DescribeDomainRecordsResponseBodyDomainRecordsRecord() + .setRR("n" + index++).setValue(entry).setRecordId("r" + index).setTTL(86400L)); + } + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(records(published.toArray( + new DescribeDomainRecordsResponseBodyDomainRecordsRecord[0]))); + + client.deploy(DOMAIN, tree); + + // The tree and DNS hold the same nodes, so add+delete is zero against a + // non-empty serverNodes set and the 0.1 threshold is not met. + verify(sdk, never()).addDomainRecord(any(AddDomainRecordRequest.class)); + verify(sdk, never()).updateDomainRecord(any(UpdateDomainRecordRequest.class)); + verify(sdk, never()).deleteDomainRecord(any(DeleteDomainRecordRequest.class)); + } + + @Test + public void deployWrapsAnySdkFailureAsADnsException() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenThrow(new RuntimeException("aliyun is down")); + + try { + client.deploy(DOMAIN, signedTree("192.168.0.1")); + Assert.fail("expected a DnsException"); + } catch (DnsException expected) { + Assert.assertEquals(DnsException.TypeEnum.DEPLOY_DOMAIN_FAILED, expected.getType()); + } + } + + @Test + public void deployRefreshesServerNodesFromDnsRatherThanTrustingTheCachedSet() throws Exception { + // deploy() clears serverNodes at the end, but collectRecords() has already + // reassigned it from the DNS response on the way in -- so asserting it is + // empty afterwards would pass no matter what deploy() did. What is worth + // pinning is that a stale cached set does not survive the round trip. + setServerNodes(new HashSet<>( + Collections.singletonList(new DnsNode(null, "10.0.0.99", null, 10000)))); + + String enr = Entry.nodesPrefix + DnsNode.compress( + Collections.singletonList(new DnsNode(null, "192.168.0.7", null, 10000))); + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(records(new DescribeDomainRecordsResponseBodyDomainRecordsRecord() + .setRR("n0").setValue(enr).setRecordId("r0").setTTL(86400L))); + + Set seen = new HashSet<>(); + Field field = AliClient.class.getDeclaredField("serverNodes"); + field.setAccessible(true); + + client.deploy(DOMAIN, signedTree("192.168.0.7")); + + // 10.0.0.99 was never in DNS, so it must be gone; and the set is emptied at + // the end of a successful deploy. + seen.addAll((Set) field.get(client)); + Assert.assertTrue(seen.isEmpty()); + } + + @Test + public void deleteDomainReportsTheStatusCode() throws Exception { + when(sdk.deleteSubDomainRecords(any( + com.aliyun.alidns20150109.models.DeleteSubDomainRecordsRequest.class))) + .thenReturn((com.aliyun.alidns20150109.models.DeleteSubDomainRecordsResponse) + new com.aliyun.alidns20150109.models.DeleteSubDomainRecordsResponse() + .setStatusCode(SUCCESS)); + + Assert.assertTrue(client.deleteDomain(DOMAIN)); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/update/AliClientTest.java b/p2p/src/test/java/org/tron/p2p/dns/update/AliClientTest.java new file mode 100644 index 00000000000..52e97929312 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/update/AliClientTest.java @@ -0,0 +1,344 @@ +package org.tron.p2p.dns.update; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.aliyun.alidns20150109.Client; +import com.aliyun.alidns20150109.models.AddDomainRecordRequest; +import com.aliyun.alidns20150109.models.AddDomainRecordResponse; +import com.aliyun.alidns20150109.models.AddDomainRecordResponseBody; +import com.aliyun.alidns20150109.models.DeleteDomainRecordRequest; +import com.aliyun.alidns20150109.models.DeleteDomainRecordResponse; +import com.aliyun.alidns20150109.models.DeleteSubDomainRecordsRequest; +import com.aliyun.alidns20150109.models.DeleteSubDomainRecordsResponse; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsRequest; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsResponse; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsResponseBody; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecords; +import com.aliyun.alidns20150109.models.DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecordsRecord; +import com.aliyun.alidns20150109.models.UpdateDomainRecordRequest; +import com.aliyun.alidns20150109.models.UpdateDomainRecordResponse; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Covers AliClient's request/retry/decision logic with the Aliyun SDK transport + * replaced by a mock. The logic under test is real — pagination, record matching, + * add-vs-update selection, retry-then-give-up — only the HTTP call is faked, since + * the alternative is a live Aliyun account. + */ +public class AliClientTest { + + private static final String DOMAIN = "example.org"; + private static final int SUCCESS = 200; + private static final int FAILURE = 500; + + private Client sdk; + private AliClient client; + + @Before + public void setUp() throws Exception { + sdk = mock(Client.class); + client = new AliClient("alidns.aliyuncs.com", "key-id", "key-secret", 0.1); + Field field = AliClient.class.getDeclaredField("aliDnsClient"); + field.setAccessible(true); + field.set(client, sdk); + } + + private static DescribeDomainRecordsResponseBodyDomainRecordsRecord record( + String rr, String value, String recordId, long ttl) { + return new DescribeDomainRecordsResponseBodyDomainRecordsRecord() + .setRR(rr).setValue(value).setRecordId(recordId).setTTL(ttl); + } + + private static DescribeDomainRecordsResponse describeResponse( + long totalCount, DescribeDomainRecordsResponseBodyDomainRecordsRecord... records) { + DescribeDomainRecordsResponseBody body = new DescribeDomainRecordsResponseBody() + .setTotalCount(totalCount) + .setDomainRecords(new DescribeDomainRecordsResponseBodyDomainRecords() + .setRecord(new ArrayList<>(Arrays.asList(records)))); + return (DescribeDomainRecordsResponse) new DescribeDomainRecordsResponse() + .setStatusCode(SUCCESS).setBody(body); + } + + private static AddDomainRecordResponse addResponse(int status, String recordId) { + return (AddDomainRecordResponse) new AddDomainRecordResponse() + .setStatusCode(status) + .setBody(new AddDomainRecordResponseBody().setRecordId(recordId)); + } + + private static UpdateDomainRecordResponse updateResponse(int status) { + return (UpdateDomainRecordResponse) new UpdateDomainRecordResponse().setStatusCode(status); + } + + private static DeleteDomainRecordResponse deleteResponse(int status) { + return (DeleteDomainRecordResponse) new DeleteDomainRecordResponse().setStatusCode(status); + } + + // ---------- addRecord / updateRecord / deleteRecord ---------- + + @Test + public void addRecordSucceedsOnFirstCall() throws Exception { + when(sdk.addDomainRecord(any(AddDomainRecordRequest.class))) + .thenReturn(addResponse(SUCCESS, "rec-1")); + + Assert.assertTrue(client.addRecord(DOMAIN, "abc", "\"value\"", 60)); + verify(sdk, times(1)).addDomainRecord(any(AddDomainRecordRequest.class)); + } + + @Test + public void addRecordGivesUpAfterRetries() throws Exception { + when(sdk.addDomainRecord(any(AddDomainRecordRequest.class))) + .thenReturn(addResponse(FAILURE, null)); + + Assert.assertFalse(client.addRecord(DOMAIN, "abc", "\"value\"", 60)); + // one initial attempt plus maxRetryCount (3) retries + verify(sdk, times(4)).addDomainRecord(any(AddDomainRecordRequest.class)); + } + + @Test + public void addRecordSucceedsOnRetry() throws Exception { + when(sdk.addDomainRecord(any(AddDomainRecordRequest.class))) + .thenReturn(addResponse(FAILURE, null)) + .thenReturn(addResponse(SUCCESS, "rec-1")); + + Assert.assertTrue(client.addRecord(DOMAIN, "abc", "\"value\"", 60)); + verify(sdk, times(2)).addDomainRecord(any(AddDomainRecordRequest.class)); + } + + @Test + public void updateRecordSucceedsAndGivesUp() throws Exception { + when(sdk.updateDomainRecord(any(UpdateDomainRecordRequest.class))) + .thenReturn(updateResponse(SUCCESS)); + Assert.assertTrue(client.updateRecord("rec-1", "abc", "\"value\"", 60)); + + when(sdk.updateDomainRecord(any(UpdateDomainRecordRequest.class))) + .thenReturn(updateResponse(FAILURE)); + Assert.assertFalse(client.updateRecord("rec-1", "abc", "\"value\"", 60)); + } + + @Test + public void deleteRecordSucceedsAndGivesUp() throws Exception { + when(sdk.deleteDomainRecord(any(DeleteDomainRecordRequest.class))) + .thenReturn(deleteResponse(SUCCESS)); + Assert.assertTrue(client.deleteRecord("rec-1")); + + when(sdk.deleteDomainRecord(any(DeleteDomainRecordRequest.class))) + .thenReturn(deleteResponse(FAILURE)); + Assert.assertFalse(client.deleteRecord("rec-1")); + } + + @Test + public void deleteDomainReportsStatus() throws Exception { + when(sdk.deleteSubDomainRecords(any(DeleteSubDomainRecordsRequest.class))) + .thenReturn((DeleteSubDomainRecordsResponse) + new DeleteSubDomainRecordsResponse().setStatusCode(SUCCESS)); + Assert.assertTrue(client.deleteDomain(DOMAIN)); + + when(sdk.deleteSubDomainRecords(any(DeleteSubDomainRecordsRequest.class))) + .thenReturn((DeleteSubDomainRecordsResponse) + new DeleteSubDomainRecordsResponse().setStatusCode(FAILURE)); + Assert.assertFalse(client.deleteDomain(DOMAIN)); + } + + // ---------- getRecId ---------- + + @Test + public void getRecIdMatchesCaseInsensitively() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(describeResponse(2, + record("other", "\"v\"", "rec-other", 60), + record("ABC", "\"v\"", "rec-abc", 60))); + + Assert.assertEquals("rec-abc", client.getRecId(DOMAIN, "abc")); + } + + @Test + public void getRecIdReturnsNullWhenNoRecords() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(describeResponse(0)); + + Assert.assertNull(client.getRecId(DOMAIN, "abc")); + } + + @Test + public void getRecIdReturnsNullWhenNoNameMatches() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(describeResponse(1, record("other", "\"v\"", "rec-other", 60))); + + Assert.assertNull(client.getRecId(DOMAIN, "abc")); + } + + @Test + public void getRecIdSwallowsSdkFailure() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenThrow(new RuntimeException("network down")); + + // the lookup is best-effort: a transport failure yields null, not a throw + Assert.assertNull(client.getRecId(DOMAIN, "abc")); + } + + // ---------- update / deleteByRR ---------- + + @Test + public void updateAddsWhenRecordIsAbsent() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(describeResponse(0)); + when(sdk.addDomainRecord(any(AddDomainRecordRequest.class))) + .thenReturn(addResponse(SUCCESS, "rec-new")); + + Assert.assertEquals("rec-new", client.update(DOMAIN, "abc", "\"value\"", 60)); + verify(sdk, times(1)).addDomainRecord(any(AddDomainRecordRequest.class)); + } + + @Test + public void updateUpdatesWhenRecordExists() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(describeResponse(1, record("abc", "\"old\"", "rec-existing", 60))); + when(sdk.updateDomainRecord(any(UpdateDomainRecordRequest.class))) + .thenReturn((UpdateDomainRecordResponse) new UpdateDomainRecordResponse() + .setStatusCode(SUCCESS) + .setBody(new com.aliyun.alidns20150109.models.UpdateDomainRecordResponseBody() + .setRecordId("rec-existing"))); + + Assert.assertEquals("rec-existing", client.update(DOMAIN, "abc", "\"new\"", 60)); + verify(sdk, times(1)).updateDomainRecord(any(UpdateDomainRecordRequest.class)); + verify(sdk, times(0)).addDomainRecord(any(AddDomainRecordRequest.class)); + } + + @Test + public void deleteByRrDeletesOnlyWhenFound() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(describeResponse(1, record("abc", "\"v\"", "rec-abc", 60))); + when(sdk.deleteDomainRecord(any(DeleteDomainRecordRequest.class))) + .thenReturn(deleteResponse(SUCCESS)); + + Assert.assertTrue(client.deleteByRR(DOMAIN, "abc")); + verify(sdk, times(1)).deleteDomainRecord(any(DeleteDomainRecordRequest.class)); + } + + @Test + public void deleteByRrIsANoOpWhenAbsent() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(describeResponse(0)); + + // nothing to delete is success, not failure + Assert.assertTrue(client.deleteByRR(DOMAIN, "abc")); + verify(sdk, times(0)).deleteDomainRecord(any(DeleteDomainRecordRequest.class)); + } + + @Test + public void deleteByRrReportsNonSuccessStatus() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(describeResponse(1, record("abc", "\"v\"", "rec-abc", 60))); + when(sdk.deleteDomainRecord(any(DeleteDomainRecordRequest.class))) + .thenReturn(deleteResponse(FAILURE)); + + Assert.assertFalse(client.deleteByRR(DOMAIN, "abc")); + } + + // ---------- collectRecords ---------- + + @Test + public void collectRecordsStripsTrailingDotAndKeysByName() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(describeResponse(2, + record("abc.", "\"v1\"", "rec-1", 60), + record("def", "\"v2\"", "rec-2", 60))); + + Map records = + client.collectRecords(DOMAIN); + + Assert.assertEquals(2, records.size()); + Assert.assertTrue("trailing dot must be stripped from the RR", records.containsKey("abc")); + Assert.assertTrue(records.containsKey("def")); + Assert.assertEquals("rec-1", records.get("abc").getRecordId()); + } + + @Test + public void collectRecordsWalksEveryPage() throws Exception { + // pageSize is 20, so a totalCount of 25 forces a second request + List page1 = new ArrayList<>(); + for (int i = 0; i < 20; i++) { + page1.add(record("n" + i, "\"v\"", "rec-" + i, 60)); + } + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(describeResponse(25, + page1.toArray(new DescribeDomainRecordsResponseBodyDomainRecordsRecord[0]))) + .thenReturn(describeResponse(25, + record("n20", "\"v\"", "rec-20", 60))); + + Map records = + client.collectRecords(DOMAIN); + + verify(sdk, times(2)).describeDomainRecords(any(DescribeDomainRecordsRequest.class)); + Assert.assertEquals(21, records.size()); + Assert.assertTrue(records.containsKey("n20")); + } + + /** + * A value carrying the nodes: prefix reaches NodesEntry.parseEntry, and one that + * fails to parse must be logged and skipped rather than aborting the collection. + * + *

    The payload here is valid URL-safe base64 whose bytes are not a valid EndPoints + * message, so decoding succeeds and the protobuf parse fails — which is the path + * NodesEntry.parseEntry actually converts into DnsException. + * + *

    Note it must be *valid* base64: Algorithm.decode64 (Algorithm.java:121) calls + * Base64.getUrlDecoder().decode() directly, which throws an unchecked + * IllegalArgumentException on malformed input. NodesEntry.parseEntry catches only + * InvalidProtocolBufferException and UnknownHostException, so that escapes both it + * and the DnsException-only catch at AliClient.collectRecords:138, aborting the whole + * collection. A single corrupt TXT record under the domain is enough. Pre-existing in + * libp2p, reported rather than fixed here. + */ + @Test + public void collectRecordsIgnoresUnparseableNodesEntry() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(describeResponse(2, + record("abc", "nodes:QUJDRA==", "rec-1", 60), + record("def", "\"v2\"", "rec-2", 60))); + + Map records = + client.collectRecords(DOMAIN); + + Assert.assertEquals(2, records.size()); + } + + @Test + public void collectRecordsPropagatesNonSuccessStatus() throws Exception { + DescribeDomainRecordsResponse failed = describeResponse(0); + failed.setStatusCode(FAILURE); + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenReturn(failed); + + try { + client.collectRecords(DOMAIN); + Assert.fail("a non-200 status must not be reported as an empty record set"); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().contains("Failed to request domain records")); + } + } + + @Test + public void collectRecordsPropagatesSdkFailure() throws Exception { + when(sdk.describeDomainRecords(any(DescribeDomainRecordsRequest.class))) + .thenThrow(new RuntimeException("network down")); + + try { + client.collectRecords(DOMAIN); + Assert.fail("a transport failure must propagate, not yield an empty map"); + } catch (Exception e) { + Assert.assertEquals("network down", e.getMessage()); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientBatchTest.java b/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientBatchTest.java new file mode 100644 index 00000000000..52f79857f5d --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientBatchTest.java @@ -0,0 +1,178 @@ +package org.tron.p2p.dns.update; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.tron.p2p.dns.update.AwsClient.RecordSet; +import org.tron.p2p.exception.DnsException; +import software.amazon.awssdk.services.route53.model.Change; +import software.amazon.awssdk.services.route53.model.ChangeAction; + +/** + * The batching side of AwsClient: Route53 caps a change batch at 32000 bytes of + * RDATA and 1000 changes, and counts an UPSERT as two. Getting the split wrong + * means a publish is rejected wholesale by the API. + */ +public class AwsClientBatchTest { + + private static AwsClient client; + private static Method splitChanges; + + @BeforeClass + public static void init() throws Exception { + client = new AwsClient("access-key", "access-secret", "zone-id", "us-east-1", 0.1); + splitChanges = AwsClient.class.getDeclaredMethod( + "splitChanges", List.class, int.class, int.class); + splitChanges.setAccessible(true); + } + + @SuppressWarnings("unchecked") + private static List> split(List changes, int sizeLimit, int countLimit) + throws Exception { + return (List>) splitChanges.invoke(null, changes, sizeLimit, countLimit); + } + + private static String repeat(char c, int n) { + StringBuilder sb = new StringBuilder(n); + for (int i = 0; i < n; i++) { + sb.append(c); + } + return sb.toString(); + } + + @Test + public void constructorRejectsMissingCredentials() { + for (String[] pair : new String[][] {{null, "secret"}, {"", "secret"}, + {"key", null}, {"key", ""}}) { + try { + new AwsClient(pair[0], pair[1], "zone-id", "us-east-1", 0.1); + Assert.fail("expected a DnsException for " + pair[0] + "/" + pair[1]); + } catch (DnsException expected) { + Assert.assertTrue(expected.getMessage().contains("Access Key")); + } + } + } + + @Test + public void everythingFitsInOneBatch() throws Exception { + List changes = new ArrayList<>(); + changes.add(client.newTXTChange(ChangeAction.CREATE, "a.example.org", 600, "aaa")); + changes.add(client.newTXTChange(ChangeAction.CREATE, "b.example.org", 600, "bbb")); + + List> batches = split(changes, 32000, 1000); + Assert.assertEquals(1, batches.size()); + Assert.assertEquals(2, batches.get(0).size()); + } + + @Test + public void sizeLimitStartsANewBatch() throws Exception { + List changes = new ArrayList<>(); + changes.add(client.newTXTChange(ChangeAction.CREATE, "a.example.org", 600, repeat('a', 60))); + changes.add(client.newTXTChange(ChangeAction.CREATE, "b.example.org", 600, repeat('b', 60))); + + // 60 bytes each, so a 100-byte limit admits exactly one per batch. + List> batches = split(changes, 100, 1000); + Assert.assertEquals(2, batches.size()); + Assert.assertEquals(1, batches.get(0).size()); + Assert.assertEquals(1, batches.get(1).size()); + } + + @Test + public void countLimitStartsANewBatch() throws Exception { + List changes = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + changes.add(client.newTXTChange(ChangeAction.CREATE, "n" + i + ".example.org", 600, "x")); + } + + List> batches = split(changes, 32000, 2); + Assert.assertEquals(3, batches.size()); + Assert.assertEquals(2, batches.get(0).size()); + Assert.assertEquals(2, batches.get(1).size()); + Assert.assertEquals(1, batches.get(2).size()); + } + + @Test + public void upsertCountsAsTwoChanges() throws Exception { + List changes = new ArrayList<>(); + changes.add(client.newTXTChange(ChangeAction.UPSERT, "a.example.org", 600, "x")); + changes.add(client.newTXTChange(ChangeAction.UPSERT, "b.example.org", 600, "x")); + + // Route53 bills an UPSERT as a delete plus a create, so a count limit of 2 + // fits only one of them. + List> batches = split(changes, 32000, 2); + Assert.assertEquals(2, batches.size()); + } + + @Test + public void emptyInputProducesNoBatches() throws Exception { + Assert.assertTrue(split(new ArrayList(), 32000, 1000).isEmpty()); + } + + @Test + public void multiValueChangeSumsItsRecordSizes() throws Exception { + List changes = new ArrayList<>(); + changes.add(client.newTXTChange(ChangeAction.CREATE, "a.example.org", 600, + repeat('a', 30), repeat('b', 30))); + changes.add(client.newTXTChange(ChangeAction.CREATE, "b.example.org", 600, "x")); + + // The first change is 60 bytes across two records, so it alone fills a + // 60-byte budget. + List> batches = split(changes, 60, 1000); + Assert.assertEquals(2, batches.size()); + } + + @Test + public void makeDeletionChangesTargetsOnlyRecordsNoLongerKept() { + Map existing = new HashMap<>(); + existing.put("keep.example.org", new RecordSet(new String[] {"a"}, 600)); + existing.put("drop.example.org", new RecordSet(new String[] {"b"}, 600)); + + Map keeps = new HashMap<>(); + keeps.put("keep.example.org", "a"); + + List deletions = client.makeDeletionChanges(keeps, existing); + Assert.assertEquals(1, deletions.size()); + Change deletion = deletions.get(0); + Assert.assertEquals(ChangeAction.DELETE, deletion.action()); + Assert.assertEquals("drop.example.org", deletion.resourceRecordSet().name()); + Assert.assertEquals(600L, deletion.resourceRecordSet().ttl().longValue()); + } + + @Test + public void makeDeletionChangesIsEmptyWhenEverythingIsKept() { + Map existing = new HashMap<>(); + existing.put("keep.example.org", new RecordSet(new String[] {"a"}, 600)); + Map keeps = new HashMap<>(); + keeps.put("keep.example.org", "a"); + + Assert.assertTrue(client.makeDeletionChanges(keeps, existing).isEmpty()); + } + + @Test + public void isSubdomainIgnoresTrailingDots() { + Assert.assertTrue(AwsClient.isSubdomain("a.example.org", "example.org")); + Assert.assertTrue(AwsClient.isSubdomain("a.example.org.", "example.org")); + Assert.assertTrue(AwsClient.isSubdomain("a.example.org", "example.org.")); + Assert.assertTrue(AwsClient.isSubdomain("example.org", "example.org")); + Assert.assertFalse(AwsClient.isSubdomain("example.org", "a.example.org")); + Assert.assertFalse(AwsClient.isSubdomain("a.example.com", "example.org")); + // Label boundaries are respected: notexample.org is not under example.org. + Assert.assertFalse(AwsClient.isSubdomain("notexample.org", "example.org")); + } + + @Test + public void newTxtChangeCarriesEveryValue() { + Change change = client.newTXTChange(ChangeAction.UPSERT, "a.example.org", 42, "one", "two"); + Assert.assertEquals(ChangeAction.UPSERT, change.action()); + Assert.assertEquals("a.example.org", change.resourceRecordSet().name()); + Assert.assertEquals(42L, change.resourceRecordSet().ttl().longValue()); + Assert.assertEquals(2, change.resourceRecordSet().resourceRecords().size()); + Assert.assertEquals("one", change.resourceRecordSet().resourceRecords().get(0).value()); + Assert.assertEquals("two", change.resourceRecordSet().resourceRecords().get(1).value()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientChangeTest.java b/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientChangeTest.java new file mode 100644 index 00000000000..0f15c021266 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientChangeTest.java @@ -0,0 +1,218 @@ +package org.tron.p2p.dns.update; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.tron.p2p.dns.update.AwsClient.RecordSet; +import software.amazon.awssdk.services.route53.model.Change; +import software.amazon.awssdk.services.route53.model.ChangeAction; + +/** + * Covers the pure change-computation side of AwsClient — the part that decides which + * Route53 records to create, update and delete for a published tree. None of it needs + * the network: the SDK client is built lazily by the constructor and is never called + * on these paths. + * + *

    TTLs come from the Publish interface: rootTTL = 600s, treeNodeTTL = 7 days. + */ +public class AwsClientChangeTest { + + private static final String DOMAIN = "example.org"; + private static final long ROOT_TTL = 10 * 60; + private static final long NODE_TTL = 7 * 24 * 60 * 60; + + private static AwsClient client; + private static Method splitTxt; + + @BeforeClass + public static void init() throws Exception { + client = new AwsClient("access-key", "access-secret", "zone-id", "us-east-1", 0.1); + splitTxt = AwsClient.class.getDeclaredMethod("splitTxt", String.class); + splitTxt.setAccessible(true); + } + + private static Map records(String... keyValues) { + Map map = new HashMap<>(); + for (int i = 0; i < keyValues.length; i += 2) { + map.put(keyValues[i], keyValues[i + 1]); + } + return map; + } + + private static Change findByName(List changes, String name) { + for (Change change : changes) { + if (change.resourceRecordSet().name().equals(name)) { + return change; + } + } + return null; + } + + @Test + public void createsRecordsThatDoNotExistYet() { + List changes = client.computeChanges(DOMAIN, + records(DOMAIN, "root-value", "abc." + DOMAIN, "leaf-value"), + new HashMap<>()); + + Assert.assertEquals(2, changes.size()); + for (Change change : changes) { + Assert.assertEquals(ChangeAction.CREATE, change.action()); + } + // the root record gets the short root TTL; everything else gets the long one + Assert.assertEquals(ROOT_TTL, + findByName(changes, DOMAIN).resourceRecordSet().ttl().longValue()); + Assert.assertEquals(NODE_TTL, + findByName(changes, "abc." + DOMAIN).resourceRecordSet().ttl().longValue()); + } + + @Test + public void leavesUnchangedRecordsAlone() { + Map existing = new HashMap<>(); + // stored values are quoted, which is what splitTxt produces + existing.put(DOMAIN, new RecordSet(new String[] {"\"root-value\""}, ROOT_TTL)); + + List changes = client.computeChanges(DOMAIN, records(DOMAIN, "root-value"), existing); + Assert.assertTrue("identical value and ttl must produce no change", changes.isEmpty()); + } + + @Test + public void upsertsWhenValueChanges() { + String leaf = "abc." + DOMAIN; + Map existing = new HashMap<>(); + existing.put(leaf, new RecordSet(new String[] {"\"old-value\""}, NODE_TTL)); + + List changes = client.computeChanges(DOMAIN, records(leaf, "new-value"), existing); + Assert.assertEquals(1, changes.size()); + Assert.assertEquals(ChangeAction.UPSERT, changes.get(0).action()); + } + + @Test + public void upsertsWhenOnlyTtlChanges() { + String leaf = "abc." + DOMAIN; + Map existing = new HashMap<>(); + // same value, wrong ttl — still needs writing back + existing.put(leaf, new RecordSet(new String[] {"\"leaf-value\""}, NODE_TTL + 1)); + + List changes = client.computeChanges(DOMAIN, records(leaf, "leaf-value"), existing); + Assert.assertEquals(1, changes.size()); + Assert.assertEquals(ChangeAction.UPSERT, changes.get(0).action()); + Assert.assertEquals(NODE_TTL, changes.get(0).resourceRecordSet().ttl().longValue()); + } + + /** + * Changing the root record takes an extra branch that tries to parse the old and new + * values as RootEntry purely to log the transition, and swallows DnsException when + * they are not parseable. Values carrying the tree-root-v1 prefix reach that parse + * and fail inside it, so this covers the catch-and-continue path. + * + *

    Note the parse is only safe here because both values are longer than the + * 13-character prefix — see RootEntry.java:67, which substrings without a length + * check and throws an unchecked StringIndexOutOfBoundsException on shorter input. + * That escapes the DnsException catch in AwsClient.computeChanges and aborts the + * whole publish. Pre-existing in libp2p, reported rather than fixed here. + */ + @Test + public void upsertsRootRecordAndIgnoresUnparseableRootEntry() { + Map existing = new HashMap<>(); + existing.put(DOMAIN, new RecordSet(new String[] {"\"tree-root-v1:AAAA\""}, ROOT_TTL)); + + List changes = client.computeChanges(DOMAIN, + records(DOMAIN, "tree-root-v1:BBBB"), existing); + Assert.assertEquals(1, changes.size()); + Assert.assertEquals(ChangeAction.UPSERT, changes.get(0).action()); + Assert.assertEquals(ROOT_TTL, changes.get(0).resourceRecordSet().ttl().longValue()); + } + + @Test + public void deletesRecordsNoLongerInTheTree() { + Map existing = new HashMap<>(); + existing.put("stale." + DOMAIN, new RecordSet(new String[] {"\"gone\""}, NODE_TTL)); + + List changes = client.makeDeletionChanges(new HashMap<>(), existing); + Assert.assertEquals(1, changes.size()); + Assert.assertEquals(ChangeAction.DELETE, changes.get(0).action()); + Assert.assertEquals("stale." + DOMAIN, changes.get(0).resourceRecordSet().name()); + + // a path that is still wanted must be kept + Assert.assertTrue( + client.makeDeletionChanges(records("stale." + DOMAIN, "still-here"), existing).isEmpty()); + } + + @Test + public void computeChangesIncludesDeletions() { + Map existing = new HashMap<>(); + existing.put("stale." + DOMAIN, new RecordSet(new String[] {"\"gone\""}, NODE_TTL)); + + List changes = client.computeChanges(DOMAIN, records(DOMAIN, "root-value"), existing); + Assert.assertEquals(2, changes.size()); + // CREATE must be ordered before DELETE + Assert.assertEquals(ChangeAction.CREATE, changes.get(0).action()); + Assert.assertEquals(ChangeAction.DELETE, changes.get(1).action()); + } + + @Test + public void sortsCreateBeforeUpsertBeforeDelete() { + List changes = new ArrayList<>(); + changes.add(client.newTXTChange(ChangeAction.DELETE, "d." + DOMAIN, NODE_TTL, "\"v\"")); + changes.add(client.newTXTChange(ChangeAction.UPSERT, "u." + DOMAIN, NODE_TTL, "\"v\"")); + changes.add(client.newTXTChange(ChangeAction.CREATE, "c." + DOMAIN, NODE_TTL, "\"v\"")); + + AwsClient.sortChanges(changes); + + Assert.assertEquals(ChangeAction.CREATE, changes.get(0).action()); + Assert.assertEquals(ChangeAction.UPSERT, changes.get(1).action()); + Assert.assertEquals(ChangeAction.DELETE, changes.get(2).action()); + } + + @Test + public void sortsByNameWithinTheSameAction() { + List changes = new ArrayList<>(); + changes.add(client.newTXTChange(ChangeAction.CREATE, "b." + DOMAIN, NODE_TTL, "\"v\"")); + changes.add(client.newTXTChange(ChangeAction.CREATE, "a." + DOMAIN, NODE_TTL, "\"v\"")); + + AwsClient.sortChanges(changes); + + Assert.assertEquals("a." + DOMAIN, changes.get(0).resourceRecordSet().name()); + Assert.assertEquals("b." + DOMAIN, changes.get(1).resourceRecordSet().name()); + } + + @Test + public void isSameChangeComparesActionNameAndValue() { + Change a = client.newTXTChange(ChangeAction.CREATE, "a." + DOMAIN, NODE_TTL, "\"v\""); + Change sameAsA = client.newTXTChange(ChangeAction.CREATE, "a." + DOMAIN, NODE_TTL, "\"v\""); + Change otherName = client.newTXTChange(ChangeAction.CREATE, "b." + DOMAIN, NODE_TTL, "\"v\""); + Change otherAction = client.newTXTChange(ChangeAction.DELETE, "a." + DOMAIN, NODE_TTL, "\"v\""); + + Assert.assertTrue(AwsClient.isSameChange(a, sameAsA)); + Assert.assertFalse(AwsClient.isSameChange(a, otherName)); + Assert.assertFalse(AwsClient.isSameChange(a, otherAction)); + } + + @Test + public void splitTxtQuotesAndChunksAt253Chars() throws Exception { + // a short value is simply wrapped in quotes + Assert.assertEquals("\"abc\"", splitTxt.invoke(client, "abc")); + Assert.assertEquals("", splitTxt.invoke(client, "")); + + // TXT strings cap at 255 bytes including the two quotes, so the payload is + // chunked every 253 characters and each chunk is quoted separately + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 300; i++) { + sb.append('x'); + } + String result = (String) splitTxt.invoke(client, sb.toString()); + + String first = sb.substring(0, 253); + String second = sb.substring(253); + Assert.assertEquals("\"" + first + "\"" + "\"" + second + "\"", result); + + // exactly 253 characters must stay a single chunk + String exact = sb.substring(0, 253); + Assert.assertEquals("\"" + exact + "\"", splitTxt.invoke(client, exact)); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientRecordsTest.java b/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientRecordsTest.java new file mode 100644 index 00000000000..8a89731062f --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientRecordsTest.java @@ -0,0 +1,232 @@ +package org.tron.p2p.dns.update; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.dns.DnsNode; +import org.tron.p2p.dns.tree.Entry; +import org.tron.p2p.dns.tree.Tree; +import org.tron.p2p.dns.update.AwsClient.RecordSet; +import software.amazon.awssdk.services.route53.Route53Client; +import software.amazon.awssdk.services.route53.model.ChangeInfo; +import software.amazon.awssdk.services.route53.model.ChangeResourceRecordSetsRequest; +import software.amazon.awssdk.services.route53.model.ChangeResourceRecordSetsResponse; +import software.amazon.awssdk.services.route53.model.ChangeStatus; +import software.amazon.awssdk.services.route53.model.GetChangeRequest; +import software.amazon.awssdk.services.route53.model.GetChangeResponse; +import software.amazon.awssdk.services.route53.model.HostedZone; +import software.amazon.awssdk.services.route53.model.ListHostedZonesByNameRequest; +import software.amazon.awssdk.services.route53.model.ListHostedZonesByNameResponse; +import software.amazon.awssdk.services.route53.model.ListResourceRecordSetsRequest; +import software.amazon.awssdk.services.route53.model.ListResourceRecordSetsResponse; +import software.amazon.awssdk.services.route53.model.RRType; +import software.amazon.awssdk.services.route53.model.ResourceRecord; +import software.amazon.awssdk.services.route53.model.ResourceRecordSet; + +/** + * The Route53-facing half of AwsClient with the SDK transport mocked: record + * collection and its pagination, zone discovery, and the publish decision that + * changeThreshold gates. Only the HTTP call is faked; the logic is real. + */ +public class AwsClientRecordsTest { + + private static final String DOMAIN = "nodes.example.org"; + private static final String PRIVATE_KEY = + "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291"; + + private Route53Client sdk; + private AwsClient client; + + @Before + public void setUp() throws Exception { + sdk = mock(Route53Client.class); + client = new AwsClient("access-key", "access-secret", "zone-id", "us-east-1", 0.1); + Field field = AwsClient.class.getDeclaredField("route53Client"); + field.setAccessible(true); + field.set(client, sdk); + } + + private static ResourceRecordSet txt(String name, long ttl, String... values) { + List records = new ArrayList<>(); + for (String value : values) { + records.add(ResourceRecord.builder().value(value).build()); + } + return ResourceRecordSet.builder() + .name(name).type(RRType.TXT).ttl(ttl).resourceRecords(records).build(); + } + + private static ListResourceRecordSetsResponse page(boolean truncated, + ResourceRecordSet... sets) { + return (ListResourceRecordSetsResponse) ListResourceRecordSetsResponse.builder() + .resourceRecordSets(Arrays.asList(sets)) + .isTruncated(truncated) + .nextRecordName("cursor") + .nextRecordType(RRType.TXT) + .build(); + } + + private static String quoted(String value) { + return "\"" + value + "\""; + } + + private static Tree signedTree(String... ips) throws Exception { + List enrs = new ArrayList<>(); + for (String ip : ips) { + enrs.add(Entry.nodesPrefix + + DnsNode.compress(Collections.singletonList(new DnsNode(null, ip, null, 10000)))); + } + Tree tree = new Tree(); + tree.makeTree(1, enrs, new ArrayList(), PRIVATE_KEY); + return tree; + } + + @Test + public void collectRecordsKeepsTxtSubdomainsAndStripsTheTrailingDot() throws Exception { + when(sdk.listResourceRecordSets(any(ListResourceRecordSetsRequest.class))).thenReturn( + page(false, + txt("a." + DOMAIN + ".", 600, quoted("hello")), + // Not a subdomain of DOMAIN, so it is skipped. + txt("other.example.com.", 600, quoted("nope")), + // Right name, wrong type. + ResourceRecordSet.builder().name("b." + DOMAIN + ".").type(RRType.A).ttl(60L) + .resourceRecords(Collections.emptyList()).build())); + + Map existing = client.collectRecords(DOMAIN); + + Assert.assertEquals(1, existing.size()); + Assert.assertTrue(existing.containsKey("a." + DOMAIN)); + } + + @Test + public void collectRecordsWalksEveryPage() throws Exception { + when(sdk.listResourceRecordSets(any(ListResourceRecordSetsRequest.class))) + .thenReturn(page(true, txt("a." + DOMAIN + ".", 600, quoted("one")))) + .thenReturn(page(false, txt("b." + DOMAIN + ".", 600, quoted("two")))); + + Map existing = client.collectRecords(DOMAIN); + + Assert.assertEquals(2, existing.size()); + verify(sdk, times(2)).listResourceRecordSets(any(ListResourceRecordSetsRequest.class)); + } + + @Test + public void collectRecordsJoinsSplitValuesBeforeParsing() throws Exception { + // Route53 stores long TXT values as several quoted chunks; they have to be + // rejoined before the entry can be recognised. + String enr = Entry.nodesPrefix + + DnsNode.compress(Collections.singletonList( + new DnsNode(null, "192.168.0.1", null, 10000))); + int half = enr.length() / 2; + when(sdk.listResourceRecordSets(any(ListResourceRecordSetsRequest.class))).thenReturn( + page(false, txt("a." + DOMAIN + ".", 600, + quoted(enr.substring(0, half)), quoted(enr.substring(half))))); + + client.collectRecords(DOMAIN); + + Field field = AwsClient.class.getDeclaredField("serverNodes"); + field.setAccessible(true); + @SuppressWarnings("unchecked") + Set serverNodes = (Set) field.get(client); + Assert.assertEquals(1, serverNodes.size()); + } + + @Test + public void malformedBase64InANodesEntryAbortsTheWholeCollection() throws Exception { + when(sdk.listResourceRecordSets(any(ListResourceRecordSetsRequest.class))).thenReturn( + page(false, txt("a." + DOMAIN + ".", 600, quoted(Entry.nodesPrefix + "!!!not-base64!!!")))); + + // The catch around parseEntry only handles DnsException, but + // Algorithm.decode64 raises an unchecked IllegalArgumentException, so a + // single corrupt TXT record takes down the entire publish rather than being + // skipped. Reported in the PR description as a deferred upstream defect and + // pinned here so a fix is visible as a test change. + try { + client.collectRecords(DOMAIN); + Assert.fail("expected the unchecked decoder failure to escape"); + } catch (IllegalArgumentException expected) { + Assert.assertTrue(expected.getMessage().contains("base64")); + } + } + + @Test + public void findZoneIdIsUsedWhenNoZoneWasConfigured() throws Exception { + AwsClient noZone = new AwsClient("access-key", "access-secret", null, "us-east-1", 0.1); + Field field = AwsClient.class.getDeclaredField("route53Client"); + field.setAccessible(true); + field.set(noZone, sdk); + + when(sdk.listHostedZonesByName(any(ListHostedZonesByNameRequest.class))).thenReturn( + (ListHostedZonesByNameResponse) ListHostedZonesByNameResponse.builder() + .hostedZones(Collections.singletonList(HostedZone.builder() + .id("/hostedzone/Z0404776204LVYA8EZNVH").name("example.org.").build())) + .isTruncated(false).build()); + when(sdk.listResourceRecordSets(any(ListResourceRecordSetsRequest.class))) + .thenReturn(page(false)); + when(sdk.changeResourceRecordSets(any(ChangeResourceRecordSetsRequest.class))) + .thenReturn(changeResponse()); + when(sdk.getChange(any(GetChangeRequest.class))).thenReturn(insync()); + + noZone.deploy(DOMAIN, signedTree("192.168.0.1")); + + Field zoneId = AwsClient.class.getDeclaredField("zoneId"); + zoneId.setAccessible(true); + Assert.assertEquals("Z0404776204LVYA8EZNVH", zoneId.get(noZone)); + } + + private static ChangeResourceRecordSetsResponse changeResponse() { + return (ChangeResourceRecordSetsResponse) ChangeResourceRecordSetsResponse.builder() + .changeInfo(ChangeInfo.builder().id("C1").status(ChangeStatus.PENDING).build()).build(); + } + + private static GetChangeResponse insync() { + return (GetChangeResponse) GetChangeResponse.builder() + .changeInfo(ChangeInfo.builder().id("C1").status(ChangeStatus.INSYNC).build()).build(); + } + + @Test + public void deployOnAnEmptyZoneSubmitsEverything() throws Exception { + when(sdk.listResourceRecordSets(any(ListResourceRecordSetsRequest.class))) + .thenReturn(page(false)); + when(sdk.changeResourceRecordSets(any(ChangeResourceRecordSetsRequest.class))) + .thenReturn(changeResponse()); + when(sdk.getChange(any(GetChangeRequest.class))).thenReturn(insync()); + + client.deploy(DOMAIN, signedTree("192.168.0.1", "192.168.0.2")); + + // serverNodes was empty, so the threshold check is bypassed entirely. + verify(sdk, times(1)).changeResourceRecordSets(any(ChangeResourceRecordSetsRequest.class)); + } + + @Test + public void submitChangesDoesNothingWhenThereIsNothingToDo() { + client.submitChanges(new ArrayList<>(), "no-op"); + verify(sdk, times(0)).changeResourceRecordSets(any(ChangeResourceRecordSetsRequest.class)); + } + + @Test + public void deleteDomainRemovesEveryCollectedRecord() throws Exception { + when(sdk.listResourceRecordSets(any(ListResourceRecordSetsRequest.class))).thenReturn( + page(false, + txt("a." + DOMAIN + ".", 600, quoted("one")), + txt("b." + DOMAIN + ".", 600, quoted("two")))); + when(sdk.changeResourceRecordSets(any(ChangeResourceRecordSetsRequest.class))) + .thenReturn(changeResponse()); + when(sdk.getChange(any(GetChangeRequest.class))).thenReturn(insync()); + + Assert.assertTrue(client.deleteDomain(DOMAIN)); + verify(sdk, times(1)).changeResourceRecordSets(any(ChangeResourceRecordSetsRequest.class)); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/update/PublishServiceTest.java b/p2p/src/test/java/org/tron/p2p/dns/update/PublishServiceTest.java new file mode 100644 index 00000000000..39df4f771f0 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/update/PublishServiceTest.java @@ -0,0 +1,208 @@ +package org.tron.p2p.dns.update; + +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Covers PublishService.checkConfig, the gate that decides whether the DNS publish + * service starts at all. Every rejection branch is exercised: a misconfigured node + * that silently starts publishing (or silently refuses to) is hard to diagnose in + * production, so each condition is pinned individually. + */ +public class PublishServiceTest { + + private static Method checkConfig; + private static PublishService service; + + @BeforeClass + public static void init() throws Exception { + checkConfig = PublishService.class.getDeclaredMethod("checkConfig", boolean.class, + PublishConfig.class); + checkConfig.setAccessible(true); + service = new PublishService(); + } + + private boolean check(boolean supportV4, PublishConfig config) throws Exception { + return (Boolean) checkConfig.invoke(service, supportV4, config); + } + + /** A config that would pass, so each test can invalidate exactly one field. */ + private PublishConfig validAliYunConfig() { + PublishConfig config = new PublishConfig(); + config.setDnsPublishEnable(true); + config.setDnsType(DnsType.AliYun); + config.setDnsDomain("nodes.example.org"); + config.setAccessKeyId("key-id"); + config.setAccessKeySecret("key-secret"); + config.setAliDnsEndpoint("alidns.aliyuncs.com"); + return config; + } + + private PublishConfig validAwsConfig() { + PublishConfig config = new PublishConfig(); + config.setDnsPublishEnable(true); + config.setDnsType(DnsType.AwsRoute53); + config.setDnsDomain("nodes.example.org"); + config.setAccessKeyId("key-id"); + config.setAccessKeySecret("key-secret"); + config.setAwsRegion("us-east-1"); + return config; + } + + @Test + public void acceptsFullyConfiguredAliYun() throws Exception { + Assert.assertTrue(check(true, validAliYunConfig())); + } + + @Test + public void acceptsFullyConfiguredAwsRoute53() throws Exception { + Assert.assertTrue(check(true, validAwsConfig())); + } + + @Test + public void rejectsWhenPublishDisabled() throws Exception { + // disabled is the default; it short-circuits before any other validation, + // so an otherwise-empty config must still be rejected without error + Assert.assertFalse(check(true, new PublishConfig())); + + PublishConfig config = validAliYunConfig(); + config.setDnsPublishEnable(false); + Assert.assertFalse(check(true, config)); + } + + @Test + public void rejectsWithoutIpV4() throws Exception { + // publishing advertises an A record, so a v4 address is required even when + // every other field is present + Assert.assertFalse(check(false, validAliYunConfig())); + Assert.assertFalse(check(false, validAwsConfig())); + } + + @Test + public void rejectsMissingDnsType() throws Exception { + PublishConfig config = validAliYunConfig(); + config.setDnsType(null); + Assert.assertFalse(check(true, config)); + } + + @Test + public void rejectsMissingDnsDomain() throws Exception { + PublishConfig config = validAliYunConfig(); + config.setDnsDomain(null); + Assert.assertFalse(check(true, config)); + + config.setDnsDomain(""); + Assert.assertFalse(check(true, config)); + } + + @Test + public void rejectsIncompleteAliYunCredentials() throws Exception { + PublishConfig noKeyId = validAliYunConfig(); + noKeyId.setAccessKeyId(null); + Assert.assertFalse(check(true, noKeyId)); + + PublishConfig noSecret = validAliYunConfig(); + noSecret.setAccessKeySecret(""); + Assert.assertFalse(check(true, noSecret)); + + PublishConfig noEndpoint = validAliYunConfig(); + noEndpoint.setAliDnsEndpoint(null); + Assert.assertFalse(check(true, noEndpoint)); + } + + @Test + public void rejectsIncompleteAwsCredentials() throws Exception { + PublishConfig noKeyId = validAwsConfig(); + noKeyId.setAccessKeyId(""); + Assert.assertFalse(check(true, noKeyId)); + + PublishConfig noSecret = validAwsConfig(); + noSecret.setAccessKeySecret(null); + Assert.assertFalse(check(true, noSecret)); + + PublishConfig noRegion = validAwsConfig(); + noRegion.setAwsRegion(null); + Assert.assertFalse(check(true, noRegion)); + } + + @Test + public void aliDnsEndpointNotRequiredForAws() throws Exception { + // the endpoint check is scoped to AliYun; an AWS config must not be rejected + // for leaving it unset + PublishConfig config = validAwsConfig(); + config.setAliDnsEndpoint(null); + Assert.assertTrue(check(true, config)); + } + + @Test + public void awsRegionNotRequiredForAliYun() throws Exception { + // and symmetrically, the region check is scoped to AwsRoute53 + PublishConfig config = validAliYunConfig(); + config.setAwsRegion(null); + Assert.assertTrue(check(true, config)); + } + + @SuppressWarnings("unchecked") + private List nodesFor(PublishConfig config) throws Exception { + Method getNodes = PublishService.class.getDeclaredMethod("getNodes", PublishConfig.class); + getNodes.setAccessible(true); + return (List) getNodes.invoke(service, config); + } + + /** + * When staticNodes are configured they are published verbatim instead of whatever the + * node happens to be connected to, so this path must not consult NodeManager at all. + * It also has to route v4 and v6 addresses into the right field of Node. + */ + @Test + public void buildsPublishableNodesFromStaticV4Addresses() throws Exception { + PublishConfig config = validAliYunConfig(); + config.setStaticNodes(Arrays.asList( + new InetSocketAddress("1.2.3.4", 18888), + new InetSocketAddress("5.6.7.8", 18889))); + + List nodes = nodesFor(config); + Assert.assertFalse(nodes.isEmpty()); + // Tree.merge emits nodes: entries, one per merged group + for (String entry : nodes) { + Assert.assertTrue("expected a nodes: entry, got " + entry, entry.startsWith("nodes:")); + } + } + + @Test + public void buildsPublishableNodesFromStaticV6Addresses() throws Exception { + PublishConfig config = validAliYunConfig(); + config.setStaticNodes(Collections.singletonList( + new InetSocketAddress("2001:db8::1", 18888))); + + List nodes = nodesFor(config); + Assert.assertFalse(nodes.isEmpty()); + Assert.assertTrue(nodes.get(0).startsWith("nodes:")); + } + + @Test + public void maxMergeSizeBoundsEachPublishedEntry() throws Exception { + PublishConfig config = validAliYunConfig(); + List statics = new ArrayList<>(); + for (int i = 0; i < 12; i++) { + statics.add(new InetSocketAddress("10.0.0." + i, 18888)); + } + config.setStaticNodes(statics); + + // 12 nodes at a merge size of 3 cannot fit in fewer than 4 entries + config.setMaxMergeSize(3); + List merged = nodesFor(config); + Assert.assertTrue("expected at least 4 entries, got " + merged.size(), merged.size() >= 4); + + // a larger merge size packs the same nodes into fewer entries + config.setMaxMergeSize(12); + Assert.assertTrue(nodesFor(config).size() <= merged.size()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/example/ExampleUsageTest.java b/p2p/src/test/java/org/tron/p2p/example/ExampleUsageTest.java new file mode 100644 index 00000000000..386c1a9471b --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/example/ExampleUsageTest.java @@ -0,0 +1,224 @@ +package org.tron.p2p.example; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.P2pEventHandler; +import org.tron.p2p.P2pService; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.dns.update.DnsType; +import org.tron.p2p.dns.update.PublishConfig; +import org.tron.p2p.exception.P2pException; +import org.tron.p2p.utils.TestPort; + +/** + * Replaces the former `example` sourceSet. + * + *

    `DnsExample1`, `DnsExample2` and `ImportUsing` documented how an embedder + * configures and drives this module. They only ever compiled — each one ended in + * a `while (true)` loop, bound a fixed port and pointed at live seed nodes, so + * nothing they demonstrated was actually checked. + * + *

    What is worth checking is the contract they advertised: that those exact + * configuration shapes are still accepted and still mean what the comments said. + * External embedders copy them, so a renamed setter or tightened validation is a + * breaking change even though nothing in this repo calls them. + */ +public class ExampleUsageTest { + + private P2pConfig saved; + private List savedHandlerList; + private java.util.Map savedHandlerMap; + + private static final byte TEST_MESSAGE_TYPE = (byte) 0x01; + + @Before + public void setUp() { + saved = Parameter.p2pConfig; + savedHandlerList = new ArrayList<>(Parameter.handlerList); + savedHandlerMap = new java.util.HashMap<>(Parameter.handlerMap); + } + + @After + public void tearDown() { + Parameter.handlerList = savedHandlerList; + Parameter.handlerMap = savedHandlerMap; + ChannelManager.isShutdown = false; + Parameter.p2pConfig = saved; + } + + /** The connection-tuning surface `ImportUsing` documented. */ + @Test + public void importUsingConfigurationShapeIsStillAccepted() { + P2pConfig config = new P2pConfig(); + config.setNetworkId(11111); + config.setPort(18888); + config.setDiscoverEnable(true); + + config.setSeedNodes(Arrays.asList( + new InetSocketAddress("13.124.62.58", 18888), + new InetSocketAddress("2600:1f13:908:1b00:e1fd:5a84:251c:a32a", 18888), + new InetSocketAddress("127.0.0.4", 18888))); + config.setActiveNodes(Arrays.asList( + new InetSocketAddress("127.0.0.2", 18888), + new InetSocketAddress("127.0.0.3", 18888))); + config.setTrustNodes(Arrays.asList( + new InetSocketAddress("127.0.0.2", 18888).getAddress())); + + config.setMinConnections(8); + config.setMinActiveConnections(2); + config.setMaxConnections(30); + config.setMaxConnectionsWithSameIp(2); + + Assert.assertEquals(11111, config.getNetworkId()); + Assert.assertEquals(18888, config.getPort()); + Assert.assertTrue(config.isDiscoverEnable()); + Assert.assertEquals(3, config.getSeedNodes().size()); + Assert.assertEquals(2, config.getActiveNodes().size()); + Assert.assertEquals(1, config.getTrustNodes().size()); + Assert.assertEquals(8, config.getMinConnections()); + Assert.assertEquals(2, config.getMinActiveConnections()); + Assert.assertEquals(30, config.getMaxConnections()); + Assert.assertEquals(2, config.getMaxConnectionsWithSameIp()); + } + + /** The register / start / query / close lifecycle `ImportUsing` walked through. */ + @Test + public void importUsingLifecycleRunsEndToEnd() throws P2pException { + P2pConfig config = new P2pConfig(); + config.setNetworkId(11111); + // The example hard-codes 18888; a test has to take a free port instead. + config.setPort(TestPort.choose()); + config.setDiscoverEnable(false); + config.setDisconnectionPolicyEnable(false); + + // messageTypes is protected, so it is set from inside the subclass — which + // is exactly how the examples did it, in their constructor. + P2pEventHandler handler = new P2pEventHandler() { + { + this.messageTypes = new HashSet<>(Arrays.asList(TEST_MESSAGE_TYPE)); + } + + @Override + public void onMessage(Channel channel, byte[] data) { + } + }; + + P2pService service = new P2pService(); + try { + service.register(handler); + service.start(config); + + Assert.assertNotNull(service.getP2pStats()); + Assert.assertNotNull(service.getAllNodes()); + Assert.assertNotNull(service.getTableNodes()); + Assert.assertNotNull(service.getConnectableNodes()); + } finally { + service.close(); + } + } + + /** Registering the same message type twice is still rejected. */ + @Test + public void duplicateMessageTypeRegistrationIsRejected() throws P2pException { + P2pEventHandler first = new P2pEventHandler() { + { + this.messageTypes = new HashSet<>(Arrays.asList(TEST_MESSAGE_TYPE)); + } + + @Override + public void onMessage(Channel channel, byte[] data) { + } + }; + Parameter.addP2pEventHandle(first); + + P2pEventHandler clash = new P2pEventHandler() { + { + this.messageTypes = new HashSet<>(Arrays.asList(TEST_MESSAGE_TYPE)); + } + + @Override + public void onMessage(Channel channel, byte[] data) { + } + }; + try { + Parameter.addP2pEventHandle(clash); + Assert.fail("expected the duplicate type to be rejected"); + } catch (P2pException expected) { + Assert.assertEquals(P2pException.TypeEnum.TYPE_ALREADY_REGISTERED, expected.getType()); + } + } + + /** The DNS *publish* shape `DnsExample1` documented. */ + @Test + public void dnsPublishConfigurationShapeIsStillAccepted() { + PublishConfig publishConfig = new PublishConfig(); + // Upstream's well-known test key, also used by AlgorithmTest. Keeping it in + // a test rather than in copyable example code is part of the point: an + // embedder must supply their own. + publishConfig.setDnsPrivate( + "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291"); + publishConfig.setDnsDomain("nodes.example.org"); + publishConfig.setKnownTreeUrls(Arrays.asList( + "tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@nodes.example1.org", + "tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@nodes.example2.org")); + publishConfig.setDnsType(DnsType.AwsRoute53); + publishConfig.setAccessKeyId("access-key"); + publishConfig.setAccessKeySecret("access-key-secret"); + publishConfig.setAwsHostZoneId("host-zone-id"); + publishConfig.setAwsRegion("us-east-1"); + publishConfig.setDnsPublishEnable(true); + + P2pConfig config = new P2pConfig(); + config.setNetworkId(11111); + config.setPort(18888); + config.setDiscoverEnable(true); + config.setPublishConfig(publishConfig); + + Assert.assertTrue(config.getPublishConfig().isDnsPublishEnable()); + Assert.assertEquals(DnsType.AwsRoute53, config.getPublishConfig().getDnsType()); + Assert.assertEquals("nodes.example.org", config.getPublishConfig().getDnsDomain()); + Assert.assertEquals(2, config.getPublishConfig().getKnownTreeUrls().size()); + Assert.assertEquals("us-east-1", config.getPublishConfig().getAwsRegion()); + } + + /** The DNS *sync* shape `DnsExample2` documented: discovery off, tree urls on. */ + @Test + public void dnsSyncConfigurationShapeIsStillAccepted() { + P2pConfig config = new P2pConfig(); + config.setDiscoverEnable(false); + config.setTreeUrls(Arrays.asList( + "tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@nodes.example.org")); + + Assert.assertFalse(config.isDiscoverEnable()); + Assert.assertEquals(1, config.getTreeUrls().size()); + // Publishing stays off unless a PublishConfig says otherwise. + Assert.assertFalse(config.getPublishConfig() != null + && config.getPublishConfig().isDnsPublishEnable()); + } + + /** Trust nodes come in as InetAddress, which is what StartApp's -t builds. */ + @Test + public void trustNodesAreInetAddresses() { + List trustNodes = new ArrayList<>(); + for (String ip : "127.0.0.2,127.0.0.3".split(",")) { + trustNodes.add(new InetSocketAddress(ip, 0).getAddress()); + } + P2pConfig config = new P2pConfig(); + config.setTrustNodes(trustNodes); + + Assert.assertEquals(2, config.getTrustNodes().size()); + Assert.assertEquals("127.0.0.2", config.getTrustNodes().get(0).getHostAddress()); + Assert.assertEquals("127.0.0.3", config.getTrustNodes().get(1).getHostAddress()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/example/StartAppArgsTest.java b/p2p/src/test/java/org/tron/p2p/example/StartAppArgsTest.java new file mode 100644 index 00000000000..11c48a2b006 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/example/StartAppArgsTest.java @@ -0,0 +1,71 @@ +package org.tron.p2p.example; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + +/** + * StartApp's command-line parsing. + * + *

    The class itself is excluded from the coverage report as a standalone entry + * point, but these two helpers are real logic and one of them shipped a bug: + * --trust-ips is declared as ip[,ip[...]] yet resolved the whole comma-separated + * value as a single hostname, so with more than one address none of the listed + * peers became trusted. + */ +public class StartAppArgsTest { + + private final StartApp app = new StartApp(); + + @Test + public void trustIpsSplitsOnComma() { + List parsed = app.parseInetAddressList("127.0.0.2,127.0.0.3"); + + Assert.assertEquals(2, parsed.size()); + Assert.assertEquals("127.0.0.2", parsed.get(0).getHostAddress()); + Assert.assertEquals("127.0.0.3", parsed.get(1).getHostAddress()); + } + + @Test + public void trustIpsAcceptsASingleAddress() { + List parsed = app.parseInetAddressList("127.0.0.2"); + Assert.assertEquals(1, parsed.size()); + Assert.assertEquals("127.0.0.2", parsed.get(0).getHostAddress()); + } + + @Test + public void trustIpsToleratesSpacesAndEmptyEntries() { + List parsed = app.parseInetAddressList(" 127.0.0.2 , ,127.0.0.3,"); + Assert.assertEquals(2, parsed.size()); + } + + @Test + public void trustIpsSkipsWhatItCannotResolve() { + // An unresolvable entry is logged and dropped rather than aborting the rest. + List parsed = + app.parseInetAddressList("127.0.0.2,no-such-host.invalid,127.0.0.3"); + Assert.assertEquals(2, parsed.size()); + Assert.assertEquals("127.0.0.2", parsed.get(0).getHostAddress()); + Assert.assertEquals("127.0.0.3", parsed.get(1).getHostAddress()); + } + + @Test + public void seedNodesParseHostAndPort() { + List parsed = + app.parseInetSocketAddressList("127.0.0.1:18888,127.0.0.2:18889"); + + Assert.assertEquals(2, parsed.size()); + Assert.assertEquals(18888, parsed.get(0).getPort()); + Assert.assertEquals("127.0.0.1", parsed.get(0).getAddress().getHostAddress()); + Assert.assertEquals(18889, parsed.get(1).getPort()); + } + + @Test + public void seedNodesAcceptBracketedIpv6() { + List parsed = app.parseInetSocketAddressList("[::1]:18888"); + Assert.assertEquals(1, parsed.size()); + Assert.assertEquals(18888, parsed.get(0).getPort()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/exception/DnsExceptionTest.java b/p2p/src/test/java/org/tron/p2p/exception/DnsExceptionTest.java new file mode 100644 index 00000000000..e9bb847c3a5 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/exception/DnsExceptionTest.java @@ -0,0 +1,40 @@ +package org.tron.p2p.exception; + +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.exception.DnsException.TypeEnum; + +public class DnsExceptionTest { + + @Test + public void messageConstructorPrefixesTheTypeDescription() { + DnsException e = new DnsException(TypeEnum.NO_ROOT_FOUND, "nile.trondisco.net"); + Assert.assertEquals(TypeEnum.NO_ROOT_FOUND, e.getType()); + Assert.assertEquals(TypeEnum.NO_ROOT_FOUND.getDesc() + ", nile.trondisco.net", + e.getMessage()); + } + + @Test + public void causeConstructorsCarryTheCause() { + Throwable cause = new IllegalArgumentException("root"); + DnsException fromCause = new DnsException(TypeEnum.INVALID_SIGNATURE, cause); + Assert.assertSame(cause, fromCause.getCause()); + Assert.assertEquals(TypeEnum.INVALID_SIGNATURE, fromCause.getType()); + + DnsException both = new DnsException(TypeEnum.INVALID_ROOT, "bad proto", cause); + Assert.assertEquals("bad proto", both.getMessage()); + Assert.assertSame(cause, both.getCause()); + } + + @Test + public void typeValuesAreDistinctAndDescribed() { + java.util.Set values = new java.util.HashSet<>(); + for (TypeEnum type : TypeEnum.values()) { + Assert.assertTrue("duplicate value for " + type, values.add(type.getValue())); + Assert.assertNotNull(type.getDesc()); + Assert.assertFalse(type.getDesc().isEmpty()); + // Note DnsException uses "-" as the separator while P2pException uses ", ". + Assert.assertEquals(type.getValue() + "-" + type.getDesc(), type.toString()); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/exception/P2pExceptionTest.java b/p2p/src/test/java/org/tron/p2p/exception/P2pExceptionTest.java new file mode 100644 index 00000000000..011da57b34e --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/exception/P2pExceptionTest.java @@ -0,0 +1,36 @@ +package org.tron.p2p.exception; + +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.exception.P2pException.TypeEnum; + +public class P2pExceptionTest { + + @Test + public void constructorsCarryTypeMessageAndCause() { + P2pException withMsg = new P2pException(TypeEnum.BAD_MESSAGE, "broken"); + Assert.assertEquals(TypeEnum.BAD_MESSAGE, withMsg.getType()); + Assert.assertEquals("broken", withMsg.getMessage()); + + Throwable cause = new IllegalStateException("root"); + P2pException withCause = new P2pException(TypeEnum.PARSE_MESSAGE_FAILED, cause); + Assert.assertEquals(TypeEnum.PARSE_MESSAGE_FAILED, withCause.getType()); + Assert.assertSame(cause, withCause.getCause()); + + P2pException both = new P2pException(TypeEnum.BIG_MESSAGE, "too big", cause); + Assert.assertEquals("too big", both.getMessage()); + Assert.assertSame(cause, both.getCause()); + } + + @Test + public void typeValuesAreDistinctAndDescribed() { + java.util.Set values = new java.util.HashSet<>(); + for (TypeEnum type : TypeEnum.values()) { + Assert.assertTrue("duplicate value for " + type, values.add(type.getValue())); + Assert.assertNotNull(type.getDesc()); + Assert.assertFalse(type.getDesc().isEmpty()); + Assert.assertEquals(type.getValue() + ", " + type.getDesc(), type.toString()); + } + Assert.assertEquals(TypeEnum.values().length, values.size()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/stats/StatsManagerTest.java b/p2p/src/test/java/org/tron/p2p/stats/StatsManagerTest.java new file mode 100644 index 00000000000..d0f1293738a --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/stats/StatsManagerTest.java @@ -0,0 +1,32 @@ +package org.tron.p2p.stats; + +import org.junit.Assert; +import org.junit.Test; + +public class StatsManagerTest { + + @Test + public void snapshotMirrorsTheLiveCounters() { + P2pStats stats = new StatsManager().getP2pStats(); + + Assert.assertEquals(TrafficStats.tcp.getInPackets().get(), stats.getTcpInPackets()); + Assert.assertEquals(TrafficStats.tcp.getOutPackets().get(), stats.getTcpOutPackets()); + Assert.assertEquals(TrafficStats.tcp.getInSize().get(), stats.getTcpInSize()); + Assert.assertEquals(TrafficStats.tcp.getOutSize().get(), stats.getTcpOutSize()); + Assert.assertEquals(TrafficStats.udp.getInPackets().get(), stats.getUdpInPackets()); + Assert.assertEquals(TrafficStats.udp.getOutPackets().get(), stats.getUdpOutPackets()); + Assert.assertEquals(TrafficStats.udp.getInSize().get(), stats.getUdpInSize()); + Assert.assertEquals(TrafficStats.udp.getOutSize().get(), stats.getUdpOutSize()); + } + + @Test + public void snapshotIsDetachedFromLaterTraffic() { + P2pStats before = new StatsManager().getP2pStats(); + long recorded = before.getTcpInPackets(); + TrafficStats.tcp.getInPackets().incrementAndGet(); + + // The old snapshot must not move with the counter. + Assert.assertEquals(recorded, before.getTcpInPackets()); + Assert.assertEquals(recorded + 1, new StatsManager().getP2pStats().getTcpInPackets()); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/stats/TrafficStatsTest.java b/p2p/src/test/java/org/tron/p2p/stats/TrafficStatsTest.java new file mode 100644 index 00000000000..7f7ac7a98eb --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/stats/TrafficStatsTest.java @@ -0,0 +1,75 @@ +package org.tron.p2p.stats; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.channel.socket.DatagramPacket; +import java.net.InetSocketAddress; +import org.junit.Assert; +import org.junit.Test; + +/** + * TrafficStats sits at the head of both the TCP and UDP pipelines and is the + * only source for the counters P2pService.getP2pStats() reports. + */ +public class TrafficStatsTest { + + private static final InetSocketAddress RECIPIENT = + new InetSocketAddress("127.0.0.1", 18888); + + @Test + public void byteBufTrafficIsCountedBothWays() { + TrafficStats.TrafficStatHandler handler = new TrafficStats.TrafficStatHandler(); + long inPackets = handler.getInPackets().get(); + long inSize = handler.getInSize().get(); + long outPackets = handler.getOutPackets().get(); + long outSize = handler.getOutSize().get(); + + EmbeddedChannel channel = + new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter()); + channel.writeInbound(Unpooled.wrappedBuffer(new byte[7])); + channel.writeOutbound(Unpooled.wrappedBuffer(new byte[11])); + + Assert.assertEquals(inPackets + 1, handler.getInPackets().get()); + Assert.assertEquals(inSize + 7, handler.getInSize().get()); + Assert.assertEquals(outPackets + 1, handler.getOutPackets().get()); + Assert.assertEquals(outSize + 11, handler.getOutSize().get()); + channel.finishAndReleaseAll(); + } + + @Test + public void datagramTrafficIsCountedByContentLength() { + TrafficStats.TrafficStatHandler handler = new TrafficStats.TrafficStatHandler(); + long inSize = handler.getInSize().get(); + + EmbeddedChannel channel = + new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter()); + ByteBuf content = Unpooled.wrappedBuffer(new byte[13]); + channel.writeInbound(new DatagramPacket(content, RECIPIENT)); + + // The datagram header is not counted, only the payload. + Assert.assertEquals(inSize + 13, handler.getInSize().get()); + channel.finishAndReleaseAll(); + } + + @Test + public void nonBufferMessagesCountAsPacketsWithoutSize() { + TrafficStats.TrafficStatHandler handler = new TrafficStats.TrafficStatHandler(); + long inPackets = handler.getInPackets().get(); + long inSize = handler.getInSize().get(); + + EmbeddedChannel channel = + new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter()); + channel.writeInbound("not a buffer"); + + Assert.assertEquals(inPackets + 1, handler.getInPackets().get()); + Assert.assertEquals(inSize, handler.getInSize().get()); + channel.finishAndReleaseAll(); + } + + @Test + public void tcpAndUdpHandlersAreSeparateInstances() { + Assert.assertNotSame(TrafficStats.tcp, TrafficStats.udp); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/utils/ByteArrayTest.java b/p2p/src/test/java/org/tron/p2p/utils/ByteArrayTest.java new file mode 100644 index 00000000000..c24e277d4de --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/utils/ByteArrayTest.java @@ -0,0 +1,167 @@ +package org.tron.p2p.utils; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.dns.update.AwsClient; + +public class ByteArrayTest { + + @Test + public void testHexToString() { + byte[] data = new byte[] {-128, -127, -1, 0, 1, 127}; + Assert.assertEquals("8081ff00017f", ByteArray.toHexString(data)); + } + + @Test + public void testToHexStringNull() { + Assert.assertEquals("", ByteArray.toHexString(null)); + } + + @Test + public void testFromHexString() { + // null yields the shared empty array rather than null + Assert.assertEquals(0, ByteArray.fromHexString(null).length); + // a 0x prefix is stripped + Assert.assertArrayEquals(new byte[] {10}, ByteArray.fromHexString("0x0a")); + // an odd-length string is left-padded with a zero nibble + Assert.assertArrayEquals(new byte[] {10}, ByteArray.fromHexString("a")); + Assert.assertArrayEquals(new byte[] {-1}, ByteArray.fromHexString("ff")); + // both together + Assert.assertArrayEquals(new byte[] {10}, ByteArray.fromHexString("0xa")); + } + + @Test + public void testToLongAndToInt() { + Assert.assertEquals(0, ByteArray.toLong(null)); + Assert.assertEquals(0, ByteArray.toLong(new byte[0])); + // unsigned big-endian: 0x0100 == 256 + Assert.assertEquals(256L, ByteArray.toLong(new byte[] {1, 0})); + // 0xff is read unsigned, not as -1 + Assert.assertEquals(255L, ByteArray.toLong(new byte[] {-1})); + + Assert.assertEquals(0, ByteArray.toInt(null)); + Assert.assertEquals(0, ByteArray.toInt(new byte[0])); + Assert.assertEquals(256, ByteArray.toInt(new byte[] {1, 0})); + } + + @Test + public void testFromStringAndToStr() { + // blank input (including whitespace-only) maps to null + Assert.assertNull(ByteArray.fromString(null)); + Assert.assertNull(ByteArray.fromString("")); + Assert.assertNull(ByteArray.fromString(" ")); + Assert.assertArrayEquals(new byte[] {97, 98}, ByteArray.fromString("ab")); + + Assert.assertNull(ByteArray.toStr(null)); + Assert.assertNull(ByteArray.toStr(new byte[0])); + Assert.assertEquals("ab", ByteArray.toStr(new byte[] {97, 98})); + } + + @Test + public void testFromLongAndFromInt() { + // big-endian, fixed width: 8 bytes for long, 4 for int + Assert.assertArrayEquals(new byte[] {0, 0, 0, 0, 0, 0, 0, 1}, ByteArray.fromLong(1L)); + Assert.assertArrayEquals(new byte[] {0, 0, 0, 1}, ByteArray.fromInt(1)); + Assert.assertArrayEquals(new byte[] {0, 0, 1, 0}, ByteArray.fromInt(256)); + } + + @Test + public void testToJsonHex() { + Assert.assertEquals("0x", ByteArray.toJsonHex((byte[]) null)); + Assert.assertEquals("0x", ByteArray.toJsonHex(new byte[0])); + Assert.assertEquals("0x0a", ByteArray.toJsonHex(new byte[] {10})); + + Assert.assertNull(ByteArray.toJsonHex((Long) null)); + Assert.assertEquals("0xff", ByteArray.toJsonHex(Long.valueOf(255L))); + Assert.assertEquals("0xff", ByteArray.toJsonHex(255)); + Assert.assertEquals("0xabc", ByteArray.toJsonHex("abc")); + } + + @Test + public void testHexToBigInteger() { + // a 0x prefix selects base 16, its absence selects base 10 + Assert.assertEquals(new BigInteger("255"), ByteArray.hexToBigInteger("0xff")); + Assert.assertEquals(new BigInteger("255"), ByteArray.hexToBigInteger("255")); + } + + @Test + public void testJsonHexToInt() throws Exception { + Assert.assertEquals(255, ByteArray.jsonHexToInt("0xff")); + try { + ByteArray.jsonHexToInt("ff"); + Assert.fail("expected a missing 0x prefix to be rejected"); + } catch (Exception e) { + Assert.assertEquals("Incorrect hex syntax", e.getMessage()); + } + } + + @Test + public void testSubArray() { + byte[] input = new byte[] {1, 2, 3, 4}; + // end is exclusive + Assert.assertArrayEquals(new byte[] {2, 3}, ByteArray.subArray(input, 1, 3)); + Assert.assertArrayEquals(new byte[0], ByteArray.subArray(input, 2, 2)); + Assert.assertArrayEquals(input, ByteArray.subArray(input, 0, 4)); + } + + @Test + public void testIsEmpty() { + Assert.assertTrue(ByteArray.isEmpty(null)); + Assert.assertTrue(ByteArray.isEmpty(new byte[0])); + Assert.assertFalse(ByteArray.isEmpty(new byte[] {0})); + } + + @Test + public void testMatrixContains() { + List source = new ArrayList<>(); + source.add(new byte[] {1, 2}); + source.add(new byte[] {3}); + // compares by content, not identity + Assert.assertTrue(ByteArray.matrixContains(source, new byte[] {1, 2})); + Assert.assertTrue(ByteArray.matrixContains(source, new byte[] {3})); + Assert.assertFalse(ByteArray.matrixContains(source, new byte[] {2, 1})); + Assert.assertFalse(ByteArray.matrixContains(new ArrayList<>(), new byte[] {1})); + } + + @Test + public void testFromHex() { + Assert.assertEquals("ab", ByteArray.fromHex("ab")); + Assert.assertEquals("ab", ByteArray.fromHex("0xab")); + // odd length is left-padded after the prefix is stripped + Assert.assertEquals("0abc", ByteArray.fromHex("0xabc")); + Assert.assertEquals("0a", ByteArray.fromHex("a")); + } + + @Test + public void testByte2int() { + // reads the byte as unsigned + Assert.assertEquals(255, ByteArray.byte2int((byte) -1)); + Assert.assertEquals(127, ByteArray.byte2int((byte) 127)); + Assert.assertEquals(0, ByteArray.byte2int((byte) 0)); + Assert.assertEquals(128, ByteArray.byte2int((byte) -128)); + } + + @Test + public void testFromObject() { + // a Serializable round-trips to a non-empty stream; two equal inputs + // serialise identically + byte[] bytes = ByteArray.fromObject("test"); + Assert.assertNotNull(bytes); + Assert.assertTrue(bytes.length > 0); + Assert.assertArrayEquals(bytes, ByteArray.fromObject("test")); + } + + @Test + public void testSubdomain() { + Assert.assertTrue(AwsClient.isSubdomain("cde.abc.com","abc.com")); + Assert.assertTrue(AwsClient.isSubdomain("cde.abc.com.","abc.com")); + Assert.assertTrue(AwsClient.isSubdomain("cde.abc.com","abc.com.")); + Assert.assertTrue(AwsClient.isSubdomain("cde.abc.com.","abc.com.")); + + Assert.assertFalse(AwsClient.isSubdomain("a-sub.abc.com","sub.abc.com")); + Assert.assertTrue(AwsClient.isSubdomain(".sub.abc.com","sub.abc.com")); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/utils/NetUtilAddressTest.java b/p2p/src/test/java/org/tron/p2p/utils/NetUtilAddressTest.java new file mode 100644 index 00000000000..1c4e2656ff0 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/utils/NetUtilAddressTest.java @@ -0,0 +1,103 @@ +package org.tron.p2p.utils; + +import com.google.protobuf.ByteString; +import java.net.InetSocketAddress; +import java.util.Set; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.discover.Node; +import org.tron.p2p.protos.Discover.Endpoint; + +/** + * Address parsing and endpoint conversion. parseInetSocketAddress reads operator + * config, and getNode converts the peer-supplied Endpoint of every discovery + * message, so both shapes of malformed input matter. + */ +public class NetUtilAddressTest { + + @Test + public void parsesIpv4WithPort() { + InetSocketAddress address = NetUtil.parseInetSocketAddress("127.0.0.1:18888"); + Assert.assertEquals("127.0.0.1", address.getAddress().getHostAddress()); + Assert.assertEquals(18888, address.getPort()); + } + + @Test + public void parsesBracketedIpv6WithPort() { + InetSocketAddress address = NetUtil.parseInetSocketAddress("[::1]:18888"); + Assert.assertEquals(18888, address.getPort()); + Assert.assertNotNull(address.getAddress()); + } + + @Test + public void tolerantOfSurroundingWhitespace() { + Assert.assertEquals(18888, + NetUtil.parseInetSocketAddress(" 127.0.0.1:18888 ".trim()).getPort()); + } + + @Test(expected = RuntimeException.class) + public void rejectsBareIpv6WithoutBrackets() { + // Ambiguous: every colon looks like a port separator. + NetUtil.parseInetSocketAddress("::1:18888"); + } + + @Test(expected = RuntimeException.class) + public void rejectsAnAddressWithNoPort() { + NetUtil.parseInetSocketAddress("127.0.0.1"); + } + + @Test(expected = NumberFormatException.class) + public void rejectsANonNumericPort() { + NetUtil.parseInetSocketAddress("127.0.0.1:notaport"); + } + + @Test + public void getNodeReadsBothAddressFamilies() { + byte[] id = NetUtil.getNodeId(); + Endpoint endpoint = Endpoint.newBuilder() + .setNodeId(ByteString.copyFrom(id)) + .setAddress(ByteString.copyFrom(ByteArray.fromString("127.0.0.1"))) + .setAddressIpv6(ByteString.copyFrom(ByteArray.fromString("::1"))) + .setPort(18888) + .build(); + + Node node = NetUtil.getNode(endpoint); + Assert.assertArrayEquals(id, node.getId()); + Assert.assertEquals("127.0.0.1", node.getHostV4()); + Assert.assertEquals(18888, node.getPort()); + } + + @Test + public void getNodeIdIsRandomAndSixtyFourBytes() { + byte[] first = NetUtil.getNodeId(); + Assert.assertEquals(64, first.length); + Assert.assertFalse(java.util.Arrays.equals(first, NetUtil.getNodeId())); + } + + @Test + public void localAddressesAlwaysIncludeLoopback() { + Set local = NetUtil.getAllLocalAddress(); + Assert.assertNotNull(local); + Assert.assertTrue("loopback should always be present", local.contains("127.0.0.1")); + for (String ip : local) { + Assert.assertFalse("zone suffixes must be stripped", ip.contains("%")); + } + } + + @Test + public void ipVersionCheckersAgreeWithTheirPatterns() { + Assert.assertTrue(NetUtil.validIpV4("127.0.0.1")); + Assert.assertTrue(NetUtil.validIpV4("255.255.255.255")); + Assert.assertFalse(NetUtil.validIpV4("256.0.0.1")); + Assert.assertFalse(NetUtil.validIpV4("127.0.0")); + Assert.assertFalse(NetUtil.validIpV4("")); + Assert.assertFalse(NetUtil.validIpV4(null)); + Assert.assertFalse(NetUtil.validIpV4("example.org")); + + Assert.assertTrue(NetUtil.validIpV6("::1")); + Assert.assertTrue(NetUtil.validIpV6("2001:db8::1")); + Assert.assertFalse(NetUtil.validIpV6("127.0.0.1")); + Assert.assertFalse(NetUtil.validIpV6("")); + Assert.assertFalse(NetUtil.validIpV6(null)); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/utils/NetUtilTest.java b/p2p/src/test/java/org/tron/p2p/utils/NetUtilTest.java new file mode 100644 index 00000000000..2b6b4daadf5 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/utils/NetUtilTest.java @@ -0,0 +1,279 @@ +package org.tron.p2p.utils; + +import com.sun.net.httpserver.HttpServer; +import java.io.OutputStream; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Set; +import org.junit.Assert; +import org.junit.Assume; +import org.junit.Test; +import org.tron.p2p.discover.Node; +import org.tron.p2p.protos.Discover; + +public class NetUtilTest { + + @Test + public void testValidIp() { + boolean flag = NetUtil.validIpV4(null); + Assert.assertFalse(flag); + flag = NetUtil.validIpV4("a.1.1.1"); + Assert.assertFalse(flag); + flag = NetUtil.validIpV4("1.1.1"); + Assert.assertFalse(flag); + flag = NetUtil.validIpV4("0.0.0.0"); + Assert.assertFalse(flag); + flag = NetUtil.validIpV4("256.1.2.3"); + Assert.assertFalse(flag); + flag = NetUtil.validIpV4("1.1.1.1"); + Assert.assertTrue(flag); + // a trailing line terminator must not be accepted (matches() vs find()) + flag = NetUtil.validIpV4("1.1.1.1\n"); + Assert.assertFalse(flag); + + flag = NetUtil.validIpV6(null); + Assert.assertFalse(flag); + flag = NetUtil.validIpV6("evil.example.com"); + Assert.assertFalse(flag); + flag = NetUtil.validIpV6("2001:db8::1"); + Assert.assertTrue(flag); + // a trailing line terminator must not be accepted (matches() vs find()) + flag = NetUtil.validIpV6("2001:db8::1\n"); + Assert.assertFalse(flag); + // a scope id may not contain whitespace (%\\S+, not %.+) + flag = NetUtil.validIpV6("fe80::1%eth0"); + Assert.assertTrue(flag); + flag = NetUtil.validIpV6("fe80::1%eth0 "); + Assert.assertFalse(flag); + flag = NetUtil.validIpV6("fe80::1%e t h0"); + Assert.assertFalse(flag); + } + + @Test + public void testValidNode() { + boolean flag = NetUtil.validNode(null); + Assert.assertFalse(flag); + + InetSocketAddress address = new InetSocketAddress("1.1.1.1", 1000); + Node node = new Node(address); + flag = NetUtil.validNode(node); + Assert.assertTrue(flag); + + node.setId(new byte[10]); + flag = NetUtil.validNode(node); + Assert.assertFalse(flag); + + node = new Node(NetUtil.getNodeId(), "1.1.1", null, 1000); + flag = NetUtil.validNode(node); + Assert.assertFalse(flag); + } + + /** + * getAllLocalAddress feeds the filter that stops a node dialling itself, so it must + * include loopback and must strip the %scope suffix that link-local IPv6 addresses + * carry — an unstripped suffix would never match the address seen on the wire. + * Enumerating local interfaces needs no external network. + */ + @Test + public void testGetAllLocalAddress() { + Set addresses = NetUtil.getAllLocalAddress(); + + Assert.assertNotNull(addresses); + Assert.assertFalse("every host has at least a loopback address", addresses.isEmpty()); + Assert.assertTrue("loopback must be present", addresses.contains("127.0.0.1")); + + for (String address : addresses) { + Assert.assertFalse("scope id must be stripped, got " + address, address.contains("%")); + Assert.assertFalse(address.isEmpty()); + } + } + + @Test + public void testGetNode() { + Discover.Endpoint endpoint = Discover.Endpoint.newBuilder() + .setPort(100).build(); + Node node = NetUtil.getNode(endpoint); + Assert.assertEquals(100, node.getPort()); + } + + /** + * getExternalIpV4 queries public IP-echo services and returns null when every one of + * them fails, so the assertions below are guarded by an assumption rather than left to + * NPE on a host with no egress. When the lookup does succeed the result must be a + * routable address: a private one would be advertised to peers that cannot reach it. + */ + @Test + public void testExternalIp() { + String ip = NetUtil.getExternalIpV4(); + Assume.assumeNotNull(ip); + + Assert.assertTrue("not a valid IPv4: " + ip, NetUtil.validIpV4(ip)); + Assert.assertFalse(ip.startsWith("10.")); + Assert.assertFalse(ip.startsWith("192.168.")); + // 172.16.0.0/12 is 172.16 through 172.31 + for (int second = 16; second <= 31; second++) { + Assert.assertFalse("private address returned: " + ip, + ip.startsWith("172." + second + ".")); + } + } + + /** + * Upstream's version of this test called three public IP-echo services and asserted + * all three returned the same string. That makes the test depend on the network and + * on the host having exactly one egress address, which is why it was unreliable + * (libp2p's own CI never ran it). It is replaced here by a loopback HTTP server, so + * the same code path — fetch, read a line, parse, validate — runs deterministically + * and the rejection branches get covered too. + */ + @Test + public void testGetIP() throws Exception { + Method method = NetUtil.class.getDeclaredMethod("getExternalIp", String.class, boolean.class); + method.setAccessible(true); + + // a well-formed IPv4 body is returned verbatim + assertExternalIp(method, "1.2.3.4\n", true, "1.2.3.4"); + // an IPv6 literal is rejected when an IPv4 address was requested + assertExternalIp(method, "2001:db8::1\n", true, null); + // an IPv4 literal is rejected when an IPv6 address was requested + assertExternalIp(method, "1.2.3.4\n", false, null); + // an empty body is rejected + assertExternalIp(method, "\n", true, null); + } + + /** + * Serves {@code body} once over loopback and asserts getExternalIp returns + * {@code expected}. Bodies are IP literals only, so no DNS lookup is triggered + * and the test stays hermetic. + */ + private void assertExternalIp(Method method, String body, boolean askIpv4, String expected) + throws Exception { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, bytes.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(bytes); + } + }); + server.start(); + try { + String url = "http://127.0.0.1:" + server.getAddress().getPort() + "/"; + Assert.assertEquals(expected, method.invoke(NetUtil.class, url, askIpv4)); + } finally { + server.stop(0); + } + } + + /** + * Upstream compared getLanIP() against the source address the kernel picks for a socket + * to www.baidu.com. Those are two different definitions of "the LAN IP": getLanIP() + * walks NetworkInterface.getNetworkInterfaces() and returns the first non-reserved IPv4 + * on an interface that is up, non-loopback and non-virtual, whereas the socket reflects + * the routing table. They disagree on any multi-homed host — a VPN or Docker bridge is + * enough — and offline the socket path falls back to 127.0.0.1 while the enumeration + * still finds the real address. This asserts the contract getLanIP() actually has, and + * needs no network. + */ + @Test + public void testGetLanIP() { + String lanIpv4 = NetUtil.getLanIP(); + + Assert.assertNotNull(lanIpv4); + Assert.assertTrue("not a valid IPv4: " + lanIpv4, NetUtil.validIpV4(lanIpv4)); + // either a usable LAN address, or the documented loopback fallback when no + // interface qualifies + if (!"127.0.0.1".equals(lanIpv4)) { + Assert.assertFalse("must not return a multicast or broadcast address", + lanIpv4.startsWith("224.") || lanIpv4.startsWith("255.")); + } + } + + @Test + public void testIPv6Format() { + String std = "fe80:0:0:0:204:61ff:fe9d:f156"; + int randomPort = 10001; + String ip1 = new InetSocketAddress("fe80:0000:0000:0000:0204:61ff:fe9d:f156", + randomPort).getAddress().getHostAddress(); + Assert.assertEquals(ip1, std); + + String ip2 = new InetSocketAddress("fe80::204:61ff:fe9d:f156", + randomPort).getAddress().getHostAddress(); + Assert.assertEquals(ip2, std); + + String ip3 = new InetSocketAddress("fe80:0000:0000:0000:0204:61ff:254.157.241.86", + randomPort).getAddress().getHostAddress(); + Assert.assertEquals(ip3, std); + + String ip4 = new InetSocketAddress("fe80:0:0:0:0204:61ff:254.157.241.86", + randomPort).getAddress().getHostAddress(); + Assert.assertEquals(ip4, std); + + String ip5 = new InetSocketAddress("fe80::204:61ff:254.157.241.86", + randomPort).getAddress().getHostAddress(); + Assert.assertEquals(ip5, std); + + String ip6 = new InetSocketAddress("FE80::204:61ff:254.157.241.86", + randomPort).getAddress().getHostAddress(); + Assert.assertEquals(ip6, std); + + String ip7 = new InetSocketAddress("[fe80:0:0:0:204:61ff:fe9d:f156]", + randomPort).getAddress().getHostAddress(); + Assert.assertEquals(ip7, std); + } + + @Test + public void testParseIpv6() { + InetSocketAddress address1 = NetUtil.parseInetSocketAddress( + "[2600:1f13:908:1b00:e1fd:5a84:251c:a32a]:18888"); + Assert.assertNotNull(address1); + Assert.assertEquals(18888, address1.getPort()); + Assert.assertEquals("2600:1f13:908:1b00:e1fd:5a84:251c:a32a", + address1.getAddress().getHostAddress()); + + try { + NetUtil.parseInetSocketAddress( + "[2600:1f13:908:1b00:e1fd:5a84:251c:a32a]:abcd"); + Assert.fail(); + } catch (RuntimeException e) { + Assert.assertTrue(true); + } + + try { + NetUtil.parseInetSocketAddress( + "2600:1f13:908:1b00:e1fd:5a84:251c:a32a:18888"); + Assert.fail(); + } catch (RuntimeException e) { + Assert.assertTrue(true); + } + + try { + NetUtil.parseInetSocketAddress( + "[2600:1f13:908:1b00:e1fd:5a84:251c:a32a:18888"); + Assert.fail(); + } catch (RuntimeException e) { + Assert.assertTrue(true); + } + + try { + NetUtil.parseInetSocketAddress( + "2600:1f13:908:1b00:e1fd:5a84:251c:a32a]:18888"); + Assert.fail(); + } catch (RuntimeException e) { + Assert.assertTrue(true); + } + + try { + NetUtil.parseInetSocketAddress( + "2600:1f13:908:1b00:e1fd:5a84:251c:a32a"); + Assert.fail(); + } catch (RuntimeException e) { + Assert.assertTrue(true); + } + + InetSocketAddress address5 = NetUtil.parseInetSocketAddress( + "192.168.0.1:18888"); + Assert.assertNotNull(address5); + } + +} diff --git a/p2p/src/test/java/org/tron/p2p/utils/ProtoUtilTest.java b/p2p/src/test/java/org/tron/p2p/utils/ProtoUtilTest.java new file mode 100644 index 00000000000..0892b6ee244 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/utils/ProtoUtilTest.java @@ -0,0 +1,30 @@ +package org.tron.p2p.utils; + +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.connection.message.keepalive.PingMessage; +import org.tron.p2p.protos.Connect; + +public class ProtoUtilTest { + + @Test + public void testCompressMessage() throws Exception { + PingMessage p1 = new PingMessage(); + + Connect.CompressMessage message = ProtoUtil.compressMessage(p1.getData()); + + byte[] d1 = ProtoUtil.uncompressMessage(message); + + PingMessage p2 = new PingMessage(d1); + + Assert.assertTrue(p1.getTimeStamp() == p2.getTimeStamp()); + + + Connect.CompressMessage m2 = ProtoUtil.compressMessage(new byte[1000]); + + byte[] d2 = ProtoUtil.uncompressMessage(m2); + + Assert.assertTrue(d2.length == 1000); + Assert.assertTrue(d2[0] == 0); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/utils/TestPort.java b/p2p/src/test/java/org/tron/p2p/utils/TestPort.java new file mode 100644 index 00000000000..e2121b8b10e --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/utils/TestPort.java @@ -0,0 +1,49 @@ +package org.tron.p2p.utils; + +import java.io.IOException; +import java.net.ServerSocket; +import java.util.Random; + +/** + * Picks a free port for tests that need to bind one. + * + *

    A fixed port collides between test classes and between the parallel forks + * Gradle runs. PeerServer.start only logs on bind failure, so a collision lets a + * test pass while exercising nothing. framework's own tests use + * org.tron.common.utils.PublicMethod.chooseRandomPort for this; :p2p cannot + * depend on :framework — that would be a cycle — so the same few lines live here. + */ +public class TestPort { + + private static final int MIN = 10240; + private static final int MAX = 65000; + private static final Random RANDOM = new Random(); + + private TestPort() { + } + + public static int choose() { + int port = next(); + try { + while (!available(port)) { + port = next(); + } + } catch (IOException e) { + return next(); + } + return port; + } + + private static int next() { + return RANDOM.nextInt(MAX - MIN + 1) + MIN; + } + + private static boolean available(int port) throws IOException { + try (ServerSocket socket = new ServerSocket(port)) { + socket.setReuseAddress(true); + return true; + } catch (IOException e) { + return false; + } + } +} diff --git a/p2p/src/test/java/org/web3j/crypto/ECDSASignatureTest.java b/p2p/src/test/java/org/web3j/crypto/ECDSASignatureTest.java new file mode 100644 index 00000000000..8361df75fb9 --- /dev/null +++ b/p2p/src/test/java/org/web3j/crypto/ECDSASignatureTest.java @@ -0,0 +1,38 @@ +package org.web3j.crypto; + +import java.math.BigInteger; +import org.junit.Assert; +import org.junit.Test; + +public class ECDSASignatureTest { + + @Test + public void lowSValueIsAlreadyCanonical() { + ECDSASignature low = new ECDSASignature(BigInteger.ONE, BigInteger.TEN); + Assert.assertTrue(low.isCanonical()); + // Nothing to adjust, so the same instance comes back. + Assert.assertSame(low, low.toCanonicalised()); + } + + @Test + public void halfCurveOrderIsStillCanonical() { + ECDSASignature edge = new ECDSASignature(BigInteger.ONE, Sign.HALF_CURVE_ORDER); + Assert.assertTrue(edge.isCanonical()); + Assert.assertSame(edge, edge.toCanonicalised()); + } + + @Test + public void highSValueIsFlippedIntoTheLowerHalf() { + BigInteger highS = Sign.HALF_CURVE_ORDER.add(BigInteger.ONE); + ECDSASignature high = new ECDSASignature(BigInteger.ONE, highS); + Assert.assertFalse(high.isCanonical()); + + ECDSASignature canonical = high.toCanonicalised(); + Assert.assertNotSame(high, canonical); + Assert.assertTrue(canonical.isCanonical()); + Assert.assertEquals(BigInteger.ONE, canonical.r); + Assert.assertEquals(Sign.CURVE.getN().subtract(highS), canonical.s); + // Canonicalising twice is a no-op. + Assert.assertSame(canonical, canonical.toCanonicalised()); + } +} diff --git a/p2p/src/test/java/org/web3j/crypto/ECKeyPairTest.java b/p2p/src/test/java/org/web3j/crypto/ECKeyPairTest.java new file mode 100644 index 00000000000..5e7cec05152 --- /dev/null +++ b/p2p/src/test/java/org/web3j/crypto/ECKeyPairTest.java @@ -0,0 +1,53 @@ +package org.web3j.crypto; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import org.junit.Assert; +import org.junit.Test; +import org.web3j.utils.Numeric; + +public class ECKeyPairTest { + + private static final BigInteger PRIVATE_KEY = new BigInteger( + "a392604efc2fad9c0b3da43b5f698a2e3f270f170d859912be0d54742275c5f6", 16); + + @Test + public void createFromBigIntegerBytesAndHexAgree() { + ECKeyPair fromBigInteger = ECKeyPair.create(PRIVATE_KEY); + ECKeyPair fromBytes = + ECKeyPair.create(Numeric.toBytesPadded(PRIVATE_KEY, 32)); + + Assert.assertEquals(PRIVATE_KEY, fromBigInteger.getPrivateKey()); + Assert.assertEquals(fromBigInteger, fromBytes); + Assert.assertEquals(fromBigInteger.hashCode(), fromBytes.hashCode()); + } + + @Test + public void equalsAndHashCode() { + ECKeyPair pair = ECKeyPair.create(PRIVATE_KEY); + ECKeyPair same = ECKeyPair.create(PRIVATE_KEY); + ECKeyPair other = ECKeyPair.create(PRIVATE_KEY.add(BigInteger.ONE)); + + Assert.assertEquals(pair, pair); + Assert.assertEquals(pair, same); + Assert.assertNotEquals(pair, other); + Assert.assertNotEquals(pair, null); + Assert.assertNotEquals(pair, "not a key pair"); + Assert.assertNotEquals(pair.hashCode(), other.hashCode()); + + ECKeyPair nulls = new ECKeyPair(null, null); + Assert.assertEquals(new ECKeyPair(null, null), nulls); + Assert.assertNotEquals(nulls, pair); + Assert.assertEquals(0, nulls.hashCode()); + } + + @Test + public void signProducesACanonicalSignature() { + byte[] hash = Hash.sha3("hello world".getBytes(StandardCharsets.UTF_8)); + ECDSASignature signature = ECKeyPair.create(PRIVATE_KEY).sign(hash); + + Assert.assertTrue(signature.isCanonical()); + Assert.assertTrue(signature.r.signum() > 0); + Assert.assertTrue(signature.s.signum() > 0); + } +} diff --git a/p2p/src/test/java/org/web3j/crypto/HashTest.java b/p2p/src/test/java/org/web3j/crypto/HashTest.java new file mode 100644 index 00000000000..9bc13f2f089 --- /dev/null +++ b/p2p/src/test/java/org/web3j/crypto/HashTest.java @@ -0,0 +1,95 @@ +package org.web3j.crypto; + +import java.nio.charset.StandardCharsets; +import org.junit.Assert; +import org.junit.Test; +import org.web3j.utils.Numeric; + +/** + * Hash is on the DNS tree signing path (Algorithm.signTree / verifySignature), + * so its digests need to stay byte-exact. Vectors are the published ones for + * each algorithm. + */ +public class HashTest { + + private static final byte[] EMPTY = new byte[0]; + + @Test + public void sha3OfEmptyInput() { + Assert.assertEquals( + "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + Numeric.toHexString(Hash.sha3(EMPTY))); + } + + @Test + public void sha3StringMatchesKnownVector() { + Assert.assertEquals( + "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad", + Hash.sha3String("hello world")); + } + + @Test + public void sha3OverARange() { + byte[] input = "hello world".getBytes(StandardCharsets.UTF_8); + byte[] whole = Hash.sha3(input); + byte[] range = Hash.sha3(input, 0, input.length); + Assert.assertArrayEquals(whole, range); + // A narrower window must produce a different digest. + Assert.assertNotEquals(Numeric.toHexString(whole), + Numeric.toHexString(Hash.sha3(input, 0, 5))); + } + + @Test + public void sha3OnHexStringRoundTrips() { + byte[] input = "hello world".getBytes(StandardCharsets.UTF_8); + Assert.assertEquals(Numeric.toHexString(Hash.sha3(input)), + Hash.sha3(Numeric.toHexString(input))); + } + + @Test + public void sha256MatchesKnownVector() { + Assert.assertEquals( + "0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + Numeric.toHexString(Hash.sha256(EMPTY))); + } + + @Test + public void hashDispatchesByAlgorithmName() { + Assert.assertArrayEquals(Hash.sha256(EMPTY), Hash.hash(EMPTY, "SHA-256")); + // The name is upper-cased before lookup, so a lowercase name resolves too. + Assert.assertArrayEquals(Hash.sha256(EMPTY), Hash.hash(EMPTY, "sha-256")); + } + + @Test(expected = RuntimeException.class) + public void hashRejectsUnknownAlgorithm() { + Hash.hash(EMPTY, "NOT-A-REAL-DIGEST"); + } + + @Test + public void sha256hash160ProducesTwentyBytes() { + byte[] out = Hash.sha256hash160("hello world".getBytes(StandardCharsets.UTF_8)); + Assert.assertEquals(20, out.length); + Assert.assertArrayEquals(out, + Hash.sha256hash160("hello world".getBytes(StandardCharsets.UTF_8))); + } + + @Test + public void hmacSha512ProducesSixtyFourBytes() { + byte[] key = "key".getBytes(StandardCharsets.UTF_8); + byte[] out = Hash.hmacSha512(key, "message".getBytes(StandardCharsets.UTF_8)); + Assert.assertEquals(64, out.length); + Assert.assertArrayEquals(out, + Hash.hmacSha512(key, "message".getBytes(StandardCharsets.UTF_8))); + Assert.assertFalse(java.util.Arrays.equals(out, + Hash.hmacSha512("other".getBytes(StandardCharsets.UTF_8), + "message".getBytes(StandardCharsets.UTF_8)))); + } + + @Test + public void blake2b256ProducesThirtyTwoBytes() { + byte[] out = Hash.blake2b256("hello world".getBytes(StandardCharsets.UTF_8)); + Assert.assertEquals(32, out.length); + Assert.assertArrayEquals(out, + Hash.blake2b256("hello world".getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/p2p/src/test/java/org/web3j/crypto/SignTest.java b/p2p/src/test/java/org/web3j/crypto/SignTest.java new file mode 100644 index 00000000000..f7aa27ee30b --- /dev/null +++ b/p2p/src/test/java/org/web3j/crypto/SignTest.java @@ -0,0 +1,117 @@ +package org.web3j.crypto; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.SignatureException; +import org.junit.Assert; +import org.junit.Test; +import org.web3j.utils.Numeric; + +/** + * secp256k1 sign / recover, which Algorithm.signTree and Algorithm.verifySignature + * use to sign and validate the DNS tree root. + */ +public class SignTest { + + private static final BigInteger PRIVATE_KEY = new BigInteger( + "a392604efc2fad9c0b3da43b5f698a2e3f270f170d859912be0d54742275c5f6", 16); + private static final byte[] MESSAGE = "hello world".getBytes(StandardCharsets.UTF_8); + + private static ECKeyPair keyPair() { + return ECKeyPair.create(PRIVATE_KEY); + } + + @Test + public void publicKeyIsDerivedDeterministicallyFromPrivate() { + BigInteger first = Sign.publicKeyFromPrivate(PRIVATE_KEY); + Assert.assertEquals(first, Sign.publicKeyFromPrivate(PRIVATE_KEY)); + Assert.assertEquals(first, keyPair().getPublicKey()); + // Uncompressed key minus the 0x04 prefix is exactly 64 bytes. Compare on the + // zero-padded form: toHexStringNoPrefix drops leading zeros, so a key whose + // X coordinate starts with a zero nibble renders shorter than 128 chars. + Assert.assertEquals(64, Numeric.toBytesPadded(first, 64).length); + Assert.assertEquals(128, Numeric.toHexStringNoPrefixZeroPadded(first, 128).length()); + } + + @Test + public void signAndRecoverRoundTrip() throws SignatureException { + ECKeyPair pair = keyPair(); + Sign.SignatureData signature = Sign.signMessage(MESSAGE, pair); + + Assert.assertEquals(32, signature.getR().length); + Assert.assertEquals(32, signature.getS().length); + Assert.assertEquals(1, signature.getV().length); + + Assert.assertEquals(pair.getPublicKey(), Sign.signedMessageToKey(MESSAGE, signature)); + } + + @Test + public void signingIsDeterministic() { + Sign.SignatureData first = Sign.signMessage(MESSAGE, keyPair()); + Sign.SignatureData second = Sign.signMessage(MESSAGE, keyPair()); + // RFC 6979 deterministic k, so the same message and key give the same bytes. + Assert.assertArrayEquals(first.getR(), second.getR()); + Assert.assertArrayEquals(first.getS(), second.getS()); + Assert.assertArrayEquals(first.getV(), second.getV()); + } + + @Test + public void aDifferentMessageRecoversADifferentKeyOrFails() { + Sign.SignatureData signature = Sign.signMessage(MESSAGE, keyPair()); + byte[] other = "goodbye world".getBytes(StandardCharsets.UTF_8); + try { + Assert.assertNotEquals(keyPair().getPublicKey(), + Sign.signedMessageToKey(other, signature)); + } catch (SignatureException expected) { + // Recovery legitimately fails for some (message, signature) pairs. + Assert.assertNotNull(expected.getMessage()); + } + } + + @Test + public void prefixedSigningRoundTrips() throws SignatureException { + ECKeyPair pair = keyPair(); + Sign.SignatureData signature = Sign.signPrefixedMessage(MESSAGE, pair); + Assert.assertEquals(pair.getPublicKey(), + Sign.signedPrefixedMessageToKey(MESSAGE, signature)); + } + + @Test + public void preHashedSigningSkipsTheDigest() throws SignatureException { + ECKeyPair pair = keyPair(); + byte[] hash = Hash.sha3(MESSAGE); + Sign.SignatureData signature = Sign.signMessage(hash, pair, false); + Assert.assertEquals(pair.getPublicKey(), Sign.signedMessageHashToKey(hash, signature)); + } + + @Test + public void recoveryRejectsAnOutOfRangeHeaderByte() { + Sign.SignatureData good = Sign.signMessage(MESSAGE, keyPair()); + Sign.SignatureData bad = + new Sign.SignatureData((byte) 0, good.getR(), good.getS()); + try { + Sign.signedMessageToKey(MESSAGE, bad); + Assert.fail("expected a SignatureException"); + } catch (SignatureException expected) { + Assert.assertTrue(expected.getMessage().contains("Header")); + } + } + + @Test + public void recoverFromSignatureReturnsNullForAnImpossibleRecId() { + ECDSASignature signature = keyPair().sign(Hash.sha3(MESSAGE)); + Assert.assertNull(Sign.recoverFromSignature(4, signature, Hash.sha3(MESSAGE))); + } + + @Test + public void signatureDataValueSemantics() { + Sign.SignatureData a = Sign.signMessage(MESSAGE, keyPair()); + Sign.SignatureData b = Sign.signMessage(MESSAGE, keyPair()); + Assert.assertEquals(a, b); + Assert.assertEquals(a.getV()[0], b.getV()[0]); + Assert.assertEquals(a.hashCode(), b.hashCode()); + Assert.assertNotEquals(a, null); + Assert.assertNotEquals(a, "not a signature"); + Assert.assertEquals(a, a); + } +} diff --git a/p2p/src/test/java/org/web3j/exceptions/MessageExceptionsTest.java b/p2p/src/test/java/org/web3j/exceptions/MessageExceptionsTest.java new file mode 100644 index 00000000000..fb398b88b69 --- /dev/null +++ b/p2p/src/test/java/org/web3j/exceptions/MessageExceptionsTest.java @@ -0,0 +1,29 @@ +package org.web3j.exceptions; + +import org.junit.Assert; +import org.junit.Test; + +public class MessageExceptionsTest { + + @Test + public void decodingExceptionCarriesMessageAndCause() { + MessageDecodingException plain = new MessageDecodingException("bad input"); + Assert.assertEquals("bad input", plain.getMessage()); + Assert.assertNull(plain.getCause()); + + Throwable cause = new IllegalStateException("root"); + MessageDecodingException wrapped = new MessageDecodingException("bad input", cause); + Assert.assertEquals("bad input", wrapped.getMessage()); + Assert.assertSame(cause, wrapped.getCause()); + } + + @Test + public void encodingExceptionCarriesMessageAndCause() { + MessageEncodingException plain = new MessageEncodingException("bad value"); + Assert.assertEquals("bad value", plain.getMessage()); + + Throwable cause = new IllegalArgumentException("root"); + MessageEncodingException wrapped = new MessageEncodingException("bad value", cause); + Assert.assertSame(cause, wrapped.getCause()); + } +} diff --git a/p2p/src/test/java/org/web3j/utils/AssertionsTest.java b/p2p/src/test/java/org/web3j/utils/AssertionsTest.java new file mode 100644 index 00000000000..65965353320 --- /dev/null +++ b/p2p/src/test/java/org/web3j/utils/AssertionsTest.java @@ -0,0 +1,22 @@ +package org.web3j.utils; + +import org.junit.Assert; +import org.junit.Test; + +public class AssertionsTest { + + @Test + public void satisfiedPreconditionIsSilent() { + Assertions.verifyPrecondition(true, "should not be thrown"); + } + + @Test + public void failedPreconditionCarriesTheMessage() { + try { + Assertions.verifyPrecondition(false, "boom"); + Assert.fail("expected a RuntimeException"); + } catch (RuntimeException e) { + Assert.assertEquals("boom", e.getMessage()); + } + } +} diff --git a/p2p/src/test/java/org/web3j/utils/NumericTest.java b/p2p/src/test/java/org/web3j/utils/NumericTest.java new file mode 100644 index 00000000000..e604ff02db1 --- /dev/null +++ b/p2p/src/test/java/org/web3j/utils/NumericTest.java @@ -0,0 +1,163 @@ +package org.web3j.utils; + +import java.math.BigDecimal; +import java.math.BigInteger; +import org.junit.Assert; +import org.junit.Test; +import org.web3j.exceptions.MessageDecodingException; +import org.web3j.exceptions.MessageEncodingException; + +/** + * Covers the message codec helpers vendored from web3j. Numeric backs Hash, Sign + * and ECKeyPair, which the DNS tree signing path depends on. + */ +public class NumericTest { + + private static final byte[] HEX_RANGE_BYTES = new byte[] {0x12, 0x34, 0x56, 0x78}; + + @Test + public void encodeQuantity() { + Assert.assertEquals("0x0", Numeric.encodeQuantity(BigInteger.ZERO)); + Assert.assertEquals("0x1", Numeric.encodeQuantity(BigInteger.ONE)); + Assert.assertEquals("0x1f4", Numeric.encodeQuantity(BigInteger.valueOf(500))); + Assert.assertEquals("0x9184e72a000", + Numeric.encodeQuantity(new BigInteger("10000000000000"))); + } + + @Test(expected = MessageEncodingException.class) + public void encodeQuantityRejectsNegative() { + Numeric.encodeQuantity(BigInteger.valueOf(-1)); + } + + @Test + public void decodeQuantity() { + Assert.assertEquals(BigInteger.ZERO, Numeric.decodeQuantity("0x0")); + Assert.assertEquals(BigInteger.valueOf(500), Numeric.decodeQuantity("0x1f4")); + Assert.assertEquals(new BigInteger("10000000000000"), + Numeric.decodeQuantity("0x9184e72a000")); + // A bare decimal string is accepted through the isLongValue path. + Assert.assertEquals(BigInteger.valueOf(123), Numeric.decodeQuantity("123")); + Assert.assertEquals(BigInteger.valueOf(-1), Numeric.decodeQuantity("-1")); + } + + @Test(expected = MessageDecodingException.class) + public void decodeQuantityRejectsNull() { + Numeric.decodeQuantity(null); + } + + @Test(expected = MessageDecodingException.class) + public void decodeQuantityRejectsTooShort() { + Numeric.decodeQuantity("0x"); + } + + @Test(expected = MessageDecodingException.class) + public void decodeQuantityRejectsMissingPrefix() { + Numeric.decodeQuantity("ff"); + } + + @Test(expected = MessageDecodingException.class) + public void decodeQuantityRejectsNonHexAfterPrefix() { + Numeric.decodeQuantity("0xzz"); + } + + @Test + public void hexPrefixHandling() { + Assert.assertTrue(Numeric.containsHexPrefix("0xff")); + Assert.assertFalse(Numeric.containsHexPrefix("ff")); + Assert.assertFalse(Numeric.containsHexPrefix("")); + Assert.assertFalse(Numeric.containsHexPrefix(null)); + Assert.assertFalse(Numeric.containsHexPrefix("0")); + + Assert.assertEquals("ff", Numeric.cleanHexPrefix("0xff")); + Assert.assertEquals("ff", Numeric.cleanHexPrefix("ff")); + Assert.assertEquals("0xff", Numeric.prependHexPrefix("ff")); + Assert.assertEquals("0xff", Numeric.prependHexPrefix("0xff")); + } + + @Test + public void toBigIntConversions() { + Assert.assertEquals(BigInteger.valueOf(0x1234), Numeric.toBigInt("0x1234")); + Assert.assertEquals(BigInteger.valueOf(0x1234), Numeric.toBigInt("1234")); + Assert.assertEquals(BigInteger.valueOf(0x1234), Numeric.toBigIntNoPrefix("1234")); + Assert.assertEquals(new BigInteger("12345678", 16), Numeric.toBigInt(HEX_RANGE_BYTES)); + Assert.assertEquals(BigInteger.valueOf(0x3456), + Numeric.toBigInt(HEX_RANGE_BYTES, 1, 2)); + // Always treated as unsigned: a leading 0xFF is not -1. + Assert.assertEquals(BigInteger.valueOf(255), Numeric.toBigInt(new byte[] {(byte) 0xFF})); + } + + @Test + public void toHexStringVariants() { + BigInteger value = BigInteger.valueOf(0x1f4); + Assert.assertEquals("0x1f4", Numeric.toHexStringWithPrefix(value)); + Assert.assertEquals("1f4", Numeric.toHexStringNoPrefix(value)); + Assert.assertEquals("0x12345678", Numeric.toHexString(HEX_RANGE_BYTES)); + Assert.assertEquals("12345678", Numeric.toHexStringNoPrefix(HEX_RANGE_BYTES)); + Assert.assertEquals("3456", Numeric.toHexString(HEX_RANGE_BYTES, 1, 2, false)); + Assert.assertEquals("0x3456", Numeric.toHexString(HEX_RANGE_BYTES, 1, 2, true)); + } + + @Test + public void toHexStringWithPrefixSafePadsSingleDigit() { + Assert.assertEquals("0x01", Numeric.toHexStringWithPrefixSafe(BigInteger.ONE)); + Assert.assertEquals("0x1f4", Numeric.toHexStringWithPrefixSafe(BigInteger.valueOf(500))); + } + + @Test + public void toHexStringZeroPadded() { + Assert.assertEquals("0x0001f4", + Numeric.toHexStringWithPrefixZeroPadded(BigInteger.valueOf(500), 6)); + Assert.assertEquals("0001f4", + Numeric.toHexStringNoPrefixZeroPadded(BigInteger.valueOf(500), 6)); + // Exact fit needs no padding. + Assert.assertEquals("1f4", Numeric.toHexStringNoPrefixZeroPadded(BigInteger.valueOf(500), 3)); + } + + @Test(expected = UnsupportedOperationException.class) + public void zeroPaddedRejectsOversizedValue() { + Numeric.toHexStringNoPrefixZeroPadded(BigInteger.valueOf(0x1f4), 2); + } + + @Test(expected = UnsupportedOperationException.class) + public void zeroPaddedRejectsNegative() { + Numeric.toHexStringNoPrefixZeroPadded(BigInteger.valueOf(-1), 20); + } + + @Test + public void toBytesPadded() { + Assert.assertArrayEquals(new byte[] {0, 0, 0x01, (byte) 0xf4}, + Numeric.toBytesPadded(BigInteger.valueOf(500), 4)); + // A value whose two's-complement form carries a leading zero byte has it dropped. + Assert.assertArrayEquals(new byte[] {0, (byte) 0xFF}, + Numeric.toBytesPadded(BigInteger.valueOf(255), 2)); + } + + @Test(expected = RuntimeException.class) + public void toBytesPaddedRejectsOversized() { + Numeric.toBytesPadded(BigInteger.valueOf(0x1f4), 1); + } + + @Test + public void hexStringToByteArray() { + Assert.assertArrayEquals(new byte[] {}, Numeric.hexStringToByteArray("")); + Assert.assertArrayEquals(HEX_RANGE_BYTES, Numeric.hexStringToByteArray("0x12345678")); + Assert.assertArrayEquals(HEX_RANGE_BYTES, Numeric.hexStringToByteArray("12345678")); + // Odd length is left-padded with a nibble rather than rejected. + Assert.assertArrayEquals(new byte[] {0x01, 0x23}, Numeric.hexStringToByteArray("123")); + } + + @Test + public void asByte() { + Assert.assertEquals((byte) 0x00, Numeric.asByte(0x0, 0x0)); + Assert.assertEquals((byte) 0x12, Numeric.asByte(0x1, 0x2)); + Assert.assertEquals((byte) 0xff, Numeric.asByte(0xf, 0xf)); + } + + @Test + public void isIntegerValue() { + Assert.assertTrue(Numeric.isIntegerValue(BigDecimal.ZERO)); + Assert.assertTrue(Numeric.isIntegerValue(BigDecimal.valueOf(5))); + Assert.assertTrue(Numeric.isIntegerValue(new BigDecimal("5.0"))); + Assert.assertFalse(Numeric.isIntegerValue(new BigDecimal("5.5"))); + } +} diff --git a/p2p/src/test/java/org/web3j/utils/StringsTest.java b/p2p/src/test/java/org/web3j/utils/StringsTest.java new file mode 100644 index 00000000000..b901a317928 --- /dev/null +++ b/p2p/src/test/java/org/web3j/utils/StringsTest.java @@ -0,0 +1,50 @@ +package org.web3j.utils; + +import java.util.Arrays; +import java.util.Collections; +import org.junit.Assert; +import org.junit.Test; + +public class StringsTest { + + @Test + public void toCsvAndJoin() { + Assert.assertEquals("a, b, c", Strings.toCsv(Arrays.asList("a", "b", "c"))); + Assert.assertEquals("a", Strings.toCsv(Collections.singletonList("a"))); + Assert.assertEquals("", Strings.toCsv(Collections.emptyList())); + Assert.assertNull(Strings.toCsv(null)); + Assert.assertEquals("a|b", Strings.join(Arrays.asList("a", "b"), "|")); + Assert.assertNull(Strings.join(null, "|")); + } + + @Test + public void capitaliseFirstLetter() { + Assert.assertEquals("Abc", Strings.capitaliseFirstLetter("abc")); + Assert.assertEquals("Abc", Strings.capitaliseFirstLetter("Abc")); + Assert.assertEquals("", Strings.capitaliseFirstLetter("")); + Assert.assertNull(Strings.capitaliseFirstLetter(null)); + } + + @Test + public void lowercaseFirstLetter() { + Assert.assertEquals("aBC", Strings.lowercaseFirstLetter("ABC")); + Assert.assertEquals("abc", Strings.lowercaseFirstLetter("abc")); + Assert.assertEquals("", Strings.lowercaseFirstLetter("")); + Assert.assertNull(Strings.lowercaseFirstLetter(null)); + } + + @Test + public void zerosAndRepeat() { + Assert.assertEquals("", Strings.zeros(0)); + Assert.assertEquals("000", Strings.zeros(3)); + Assert.assertEquals("xxxx", Strings.repeat('x', 4)); + } + + @Test + public void isEmpty() { + Assert.assertTrue(Strings.isEmpty(null)); + Assert.assertTrue(Strings.isEmpty("")); + Assert.assertFalse(Strings.isEmpty(" ")); + Assert.assertFalse(Strings.isEmpty("a")); + } +} diff --git a/plugins/build.gradle b/plugins/build.gradle index 09a13a19b1b..ee43646dadd 100644 --- a/plugins/build.gradle +++ b/plugins/build.gradle @@ -5,9 +5,7 @@ plugins { apply plugin: 'application' apply plugin: 'checkstyle' -def versions = [ - checkstyle: '8.7', -] + mainClassName = 'org.tron.plugins.ArchiveManifest' group 'org.tron' version '1.0.0' @@ -35,7 +33,10 @@ dependencies { testImplementation project(":framework") testImplementation project(":framework").sourceSets.test.output implementation(project(":crypto")) { - exclude group: 'io.github.tronprotocol', module: 'libp2p' + // :p2p arrives through :crypto -> :common (`api project(":p2p")`). Neither + // Toolkit nor ArchiveManifest uses it, so keep it and its DNS-publish SDKs + // (Route53, Aliyun) out of both fat jars, as the libp2p exclude did before. + exclude group: 'java-tron', module: 'p2p' exclude group: 'io.prometheus' exclude group: 'org.aspectj' exclude group: 'org.apache.httpcomponents' @@ -75,7 +76,7 @@ dependencies { check.dependsOn 'lint' checkstyle { - toolVersion = "${versions.checkstyle}" + toolVersion = "${rootProject.checkstyleVersion}" configFile = file("../framework/config/checkstyle/checkStyleAll.xml") maxWarnings = 0 } diff --git a/plugins/src/main/resources/logback.xml b/plugins/src/main/resources/logback.xml index fa557f1a412..3f5eff3a1e0 100644 --- a/plugins/src/main/resources/logback.xml +++ b/plugins/src/main/resources/logback.xml @@ -3,16 +3,7 @@ - - - - - %d{HH:mm:ss.SSS} %-5level [%t] [%c{1}]\(%F:%L\) %m%n - - - INFO - - + diff --git a/protocol/build.gradle b/protocol/build.gradle index ed8914343b8..62c18db6248 100644 --- a/protocol/build.gradle +++ b/protocol/build.gradle @@ -1,11 +1,10 @@ apply plugin: 'com.google.protobuf' apply from: 'protoLint.gradle' -def protobufVersion = '3.25.8' dependencies { - api group: 'com.google.protobuf', name: 'protobuf-java', version: protobufVersion - api group: 'com.google.protobuf', name: 'protobuf-java-util', version: protobufVersion + api group: 'com.google.protobuf', name: 'protobuf-java', version: rootProject.protobufVersion + api group: 'com.google.protobuf', name: 'protobuf-java-util', version: rootProject.protobufVersion api group: 'net.jcip', name: 'jcip-annotations', version: '1.0' // checkstyleConfig "com.puppycrawl.tools:checkstyle:${versions.checkstyle}" @@ -41,7 +40,7 @@ sourceSets { protobuf { generatedFilesBaseDir = "$projectDir/src/" protoc { - artifact = "com.google.protobuf:protoc:${protobufVersion}" + artifact = "com.google.protobuf:protoc:${rootProject.protobufVersion}" } plugins { diff --git a/protocol/src/main/protos/api/api.proto b/protocol/src/main/protos/api/api.proto index f8d13a6bbd3..515fa4222c2 100644 --- a/protocol/src/main/protos/api/api.proto +++ b/protocol/src/main/protos/api/api.proto @@ -613,21 +613,6 @@ service WalletSolidity { } }; -service WalletExtension { - //Please use GetTransactionsFromThis2 instead of this function. - rpc GetTransactionsFromThis (AccountPaginated) returns (TransactionList) { - } - //Use this function instead of GetTransactionsFromThis. - rpc GetTransactionsFromThis2 (AccountPaginated) returns (TransactionListExtention) { - } - //Please use GetTransactionsToThis2 instead of this function. - rpc GetTransactionsToThis (AccountPaginated) returns (TransactionList) { - } - //Use this function instead of GetTransactionsToThis. - rpc GetTransactionsToThis2 (AccountPaginated) returns (TransactionListExtention) { - } -}; - // the api of tron's db service Database { // for tapos @@ -699,9 +684,6 @@ message AssetIssueList { message BlockList { repeated Block block = 1; } -message TransactionList { - repeated Transaction transaction = 1; -} message TransactionIdList { repeated string txId = 1; } @@ -764,10 +746,6 @@ message NumberMessage { message BytesMessage { bytes value = 1; } -message TimeMessage { - int64 beginInMilliseconds = 1; - int64 endInMilliseconds = 2; -} message BlockReq { string id_or_num = 1; bool detail = 2; @@ -780,16 +758,6 @@ message TransactionLimit { bytes transactionId = 1; int64 limitNum = 2; } -message AccountPaginated { - Account account = 1; - int64 offset = 2; - int64 limit = 3; -} -message TimePaginatedMessage { - TimeMessage timeMessage = 1; - int64 offset = 2; - int64 limit = 3; -} //deprecated message AccountNetMessage { int64 freeNetUsed = 1; @@ -854,10 +822,6 @@ message BlockListExtention { repeated BlockExtention block = 1; } -message TransactionListExtention { - repeated TransactionExtention transaction = 1; -} - message BlockIncrementalMerkleTree { int64 number = 1; IncrementalMerkleTree merkleTree = 2; diff --git a/protocol/src/main/protos/core/contract/account_contract.proto b/protocol/src/main/protos/core/contract/account_contract.proto index d3180048f43..05e7226329c 100644 --- a/protocol/src/main/protos/core/contract/account_contract.proto +++ b/protocol/src/main/protos/core/contract/account_contract.proto @@ -29,7 +29,7 @@ message AccountCreateContract { AccountType type = 3; } -// Update account name. Account name is not unique now. +// Update account name. ALLOW_UPDATE_ACCOUNT_NAME is not enabled on Mainnet, so account names are currently unique. message AccountUpdateContract { bytes account_name = 1; bytes owner_address = 2; @@ -47,4 +47,3 @@ message AccountPermissionUpdateContract { Permission witness = 3; //Can be empty repeated Permission actives = 4; //Empty is invalidate } - diff --git a/settings.gradle b/settings.gradle index 0a1fd84bdf9..94339269e11 100644 --- a/settings.gradle +++ b/settings.gradle @@ -15,5 +15,6 @@ include 'example:actuator-example' include 'crypto' include 'plugins' include 'platform' +include 'p2p' include 'errorprone'